博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java科普之加密算法
阅读量:4970 次
发布时间:2019-06-12

本文共 17079 字,大约阅读时间需要 56 分钟。

       本文来自 ,引用必须注明出处!

加密比较复杂,但今天公司有需求,就稍微再研究一下,方式只有两种,对称加密和非对称加密。对称加密是指加密后可以用原方法解密,如情报传输常用;非对称加密指加密后不可解密,有什么用途呢?登录的密码使用非对称加密,拿到加密后数据跟数据库存的数据对比,相同则让登录成功(也就说数据库不存明文密码,只存加密后的字符串),还有接口参数的校验等,例如md5参数校验;有了这种加密方式再不也担心用户名密码被盗了(除非密码本被盗等其他情况)。下面我们介绍几种常见的加密方法

通用的Base64

public class Base64 {    static private final int BASELENGTH = 128;    static private final int LOOKUPLENGTH = 64;    static private final int TWENTYFOURBITGROUP = 24;    static private final int EIGHTBIT = 8;    static private final int SIXTEENBIT = 16;    static private final int FOURBYTE = 4;    static private final int SIGN = -128;    static private final char PAD = '=';    static private final boolean fDebug = false;    static final private byte[] base64Alphabet = new byte[BASELENGTH];    static final private char[] lookUpBase64Alphabet = new char[LOOKUPLENGTH];    static {        for (int i = 0; i < BASELENGTH; ++i) {            base64Alphabet[i] = -1;        }        for (int i = 'Z'; i >= 'A'; i--) {            base64Alphabet[i] = (byte) (i - 'A');        }        for (int i = 'z'; i >= 'a'; i--) {            base64Alphabet[i] = (byte) (i - 'a' + 26);        }        for (int i = '9'; i >= '0'; i--) {            base64Alphabet[i] = (byte) (i - '0' + 52);        }        base64Alphabet['+'] = 62;        base64Alphabet['/'] = 63;        for (int i = 0; i <= 25; i++) {            lookUpBase64Alphabet[i] = (char) ('A' + i);        }        for (int i = 26, j = 0; i <= 51; i++, j++) {            lookUpBase64Alphabet[i] = (char) ('a' + j);        }        for (int i = 52, j = 0; i <= 61; i++, j++) {            lookUpBase64Alphabet[i] = (char) ('0' + j);        }        lookUpBase64Alphabet[62] = (char) '+';        lookUpBase64Alphabet[63] = (char) '/';    }    private static boolean isWhiteSpace(char octect) {        return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9);    }    private static boolean isPad(char octect) {        return (octect == PAD);    }    private static boolean isData(char octect) {        return (octect < BASELENGTH && base64Alphabet[octect] != -1);    }    /**     * Encodes hex octects into Base64     *     * @param binaryData Array containing binaryData     * @return Encoded Base64 array     */    public static String encode(byte[] binaryData) {        if (binaryData == null) {            return null;        }        int lengthDataBits = binaryData.length * EIGHTBIT;        if (lengthDataBits == 0) {            return "";        }        int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;        int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP;        int numberQuartet = fewerThan24bits != 0 ? numberTriplets + 1                : numberTriplets;        char encodedData[] = null;        encodedData = new char[numberQuartet * 4];        byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0;        int encodedIndex = 0;        int dataIndex = 0;        if (fDebug) {            System.out.println("number of triplets = " + numberTriplets);        }        for (int i = 0; i < numberTriplets; i++) {            b1 = binaryData[dataIndex++];            b2 = binaryData[dataIndex++];            b3 = binaryData[dataIndex++];            if (fDebug) {                System.out.println("b1= " + b1 + ", b2= " + b2 + ", b3= " + b3);            }            l = (byte) (b2 & 0x0f);            k = (byte) (b1 & 0x03);            byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2)                    : (byte) ((b1) >> 2 ^ 0xc0);            byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4)                    : (byte) ((b2) >> 4 ^ 0xf0);            byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6)                    : (byte) ((b3) >> 6 ^ 0xfc);            if (fDebug) {                System.out.println("val2 = " + val2);                System.out.println("k4   = " + (k << 4));                System.out.println("vak  = " + (val2 | (k << 4)));            }            encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];            encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];            encodedData[encodedIndex++] = lookUpBase64Alphabet[(l << 2) | val3];            encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f];        }        // form integral number of 6-bit groups        if (fewerThan24bits == EIGHTBIT) {            b1 = binaryData[dataIndex];            k = (byte) (b1 & 0x03);            if (fDebug) {                System.out.println("b1=" + b1);                System.out.println("b1<<2 = " + (b1 >> 2));            }            byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2)                    : (byte) ((b1) >> 2 ^ 0xc0);            encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];            encodedData[encodedIndex++] = lookUpBase64Alphabet[k << 4];            encodedData[encodedIndex++] = PAD;            encodedData[encodedIndex++] = PAD;        } else if (fewerThan24bits == SIXTEENBIT) {            b1 = binaryData[dataIndex];            b2 = binaryData[dataIndex + 1];            l = (byte) (b2 & 0x0f);            k = (byte) (b1 & 0x03);            byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2)                    : (byte) ((b1) >> 2 ^ 0xc0);            byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4)                    : (byte) ((b2) >> 4 ^ 0xf0);            encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];            encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];            encodedData[encodedIndex++] = lookUpBase64Alphabet[l << 2];            encodedData[encodedIndex++] = PAD;        }        return new String(encodedData);    }    /**     * Decodes Base64 data into octects     *     * @param encoded string containing Base64 data     * @return Array containind decoded data.     */    public static byte[] decode(String encoded) {        if (encoded == null) {            return null;        }        char[] base64Data = encoded.toCharArray();        // remove white spaces        int len = removeWhiteSpace(base64Data);        if (len % FOURBYTE != 0) {            return null;// should be divisible by four        }        int numberQuadruple = (len / FOURBYTE);        if (numberQuadruple == 0) {            return new byte[0];        }        byte decodedData[] = null;        byte b1 = 0, b2 = 0, b3 = 0, b4 = 0;        char d1 = 0, d2 = 0, d3 = 0, d4 = 0;        int i = 0;        int encodedIndex = 0;        int dataIndex = 0;        decodedData = new byte[(numberQuadruple) * 3];        for (; i < numberQuadruple - 1; i++) {            if (!isData((d1 = base64Data[dataIndex++]))                    || !isData((d2 = base64Data[dataIndex++]))                    || !isData((d3 = base64Data[dataIndex++]))                    || !isData((d4 = base64Data[dataIndex++]))) {                return null;            }// if found "no data" just return null            b1 = base64Alphabet[d1];            b2 = base64Alphabet[d2];            b3 = base64Alphabet[d3];            b4 = base64Alphabet[d4];            decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);            decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));            decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);        }        if (!isData((d1 = base64Data[dataIndex++]))                || !isData((d2 = base64Data[dataIndex++]))) {            return null;// if found "no data" just return null        }        b1 = base64Alphabet[d1];        b2 = base64Alphabet[d2];        d3 = base64Data[dataIndex++];        d4 = base64Data[dataIndex++];        if (!isData((d3)) || !isData((d4))) {// Check if they are PAD characters            if (isPad(d3) && isPad(d4)) {                if ((b2 & 0xf) != 0)// last 4 bits should be zero                {                    return null;                }                byte[] tmp = new byte[i * 3 + 1];                System.arraycopy(decodedData, 0, tmp, 0, i * 3);                tmp[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);                return tmp;            } else if (!isPad(d3) && isPad(d4)) {                b3 = base64Alphabet[d3];                if ((b3 & 0x3) != 0)// last 2 bits should be zero                {                    return null;                }                byte[] tmp = new byte[i * 3 + 2];                System.arraycopy(decodedData, 0, tmp, 0, i * 3);                tmp[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);                tmp[encodedIndex] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));                return tmp;            } else {                return null;            }        } else { // No PAD e.g 3cQl            b3 = base64Alphabet[d3];            b4 = base64Alphabet[d4];            decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);            decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));            decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);        }        return decodedData;    }    /**     * remove WhiteSpace from MIME containing encoded Base64 data.     *     * @param data the byte array of base64 data (with WS)     * @return the new length     */    private static int removeWhiteSpace(char[] data) {        if (data == null) {            return 0;        }        // count characters that's not whitespace        int newSize = 0;        int len = data.length;        for (int i = 0; i < len; i++) {            if (!isWhiteSpace(data[i])) {                data[newSize++] = data[i];            }        }        return newSize;    }}

Md5加密,主要用于C端对参数加密后做一个签名,然后S端采取同样操作,签名一致则认为安全,返回数据;目的,为了防止恶意添加参数,盗取数据;原理:非对称加密,加密过程单向不可逆,比较加密后的结果;应用方式,下面是通用的密码本,所以很容易破解,当然也可以自定义密码本(C/S一致即可)。

// 全局数组    private final static String[] strDigits = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};    protected static char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};    // 返回形式为数字跟字符串    private static String byteToArrayString(byte bByte) {        int iRet = bByte;        // System.out.println("iRet="+iRet);        if (iRet < 0) {            iRet += 256;        }        int iD1 = iRet / 16;        int iD2 = iRet % 16;        return strDigits[iD1] + strDigits[iD2];    }    // 转换字节数组为16进制字串    private static String byteToString(byte[] bByte) {        StringBuffer sBuffer = new StringBuffer();        for (int i = 0; i < bByte.length; i++) {            sBuffer.append(byteToArrayString(bByte[i]));        }        return sBuffer.toString();    }    public static String MD5Encrypt(String strObj) {        String resultString = null;        try {            resultString = new String(strObj);            MessageDigest md = MessageDigest.getInstance("MD5");            // md.digest() 该函数返回值为存放哈希值结果的byte数组            resultString = byteToString(md.digest(strObj.getBytes()));        } catch (NoSuchAlgorithmException ex) {            ex.printStackTrace();        }        return resultString;    }

Des加密-(Data Encryption Standard),由56位密钥和8位奇偶检验符组成,通过异或、移位、置换和代换四种操作循环完成,如果一台PC计算能力是一秒一百万次,那么需要2000年才能破解,破解的方案只有穷举法猜出它的密码本或者暴力方式。特别说明一点,使用DES加密的KEY只有前8位有效,写多了也是多余。对称加密,加密方式可逆,用于双方各持有的一个密码本,一个加密一个解密,二战期间的情报加密方式类似这种。

private static String encoding = "UTF-8";	/**	 * sKey 奇偶校验位  加密字符串	 */	public static String encrypTo(String sKey, String str) {		String result = str;		if (str != null && str.length() > 0) {			try {				byte[] encodeByte = str.getBytes(encoding);				byte[] encoder = getSymmetricResult(Cipher.ENCRYPT_MODE, sKey, encodeByte);				result = Base64.encode(encoder).toString();			} catch (Exception e) {				e.printStackTrace();				return "";			}		}		return result;	}	/**	 * sKey 奇偶校验位	 * 解密字符串	 */	public static String decrypTo(String sKey, String str) {		String result = str;		if (str != null && str.length() > 0) {			try {				byte[] decodeByte = Base64.decode(str);				byte[] decoder = getSymmetricResult(Cipher.DECRYPT_MODE, sKey, decodeByte);				result = new String(decoder, encoding);			} catch (Exception e) {				e.printStackTrace();				return "";			}		}		return result;	}	/**	 * 对称加密字节数组并返回	 * 	 * @param byteSource	 *            需要加密的数据	 * @return 经过加密的数据	 * @throws Exception	 */	public static byte[] getSymmetricResult(int mode, String sKey, byte[] byteSource) throws Exception {		try {			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");			byte[] keyData = sKey.getBytes();			DESKeySpec keySpec = new DESKeySpec(keyData);			Key key = keyFactory.generateSecret(keySpec);			Cipher cipher = Cipher.getInstance("DES");			cipher.init(mode, key);			byte[] result = cipher.doFinal(byteSource);			return result;		} catch (Exception e) {			throw e;		} finally {		}	}

AES加密(Advanced Encryption Start)-DES的升级版本,密钥长度可能是128位、192位和256位中的一种,使用更为复杂的算法,对称加密,同样也是可逆的,但由于复杂度加大解密时间更长。

/**	 * 加密	 * 	 * @param content	 *            需要加密的内容	 * @param password	 *            加密密码	 * @return	 */	public static byte[] encrypt(String password, String content) {		try {			KeyGenerator kgen = KeyGenerator.getInstance("AES");			kgen.init(128, new SecureRandom(password.getBytes()));			SecretKey secretKey = kgen.generateKey();			byte[] enCodeFormat = secretKey.getEncoded();			SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");			Cipher cipher = Cipher.getInstance("AES");// 创建密码器			byte[] byteContent = content.getBytes("utf-8");			cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化			byte[] result = cipher.doFinal(byteContent);			return result; // 加密		} catch (NoSuchAlgorithmException e) {			e.printStackTrace();		} catch (NoSuchPaddingException e) {			e.printStackTrace();		} catch (InvalidKeyException e) {			e.printStackTrace();		} catch (UnsupportedEncodingException e) {			e.printStackTrace();		} catch (IllegalBlockSizeException e) {			e.printStackTrace();		} catch (BadPaddingException e) {			e.printStackTrace();		}		return null;	}	/**	 * 解密	 * 	 * @param content	 *            待解密内容	 * @param password	 *            解密密钥	 * @return	 */	public static byte[] decrypt(String password, byte[] content) {		try {			KeyGenerator kgen = KeyGenerator.getInstance("AES");			kgen.init(128, new SecureRandom(password.getBytes()));			SecretKey secretKey = kgen.generateKey();			byte[] enCodeFormat = secretKey.getEncoded();			SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");			Cipher cipher = Cipher.getInstance("AES");// 创建密码器			cipher.init(Cipher.DECRYPT_MODE, key);// 初始化			byte[] result = cipher.doFinal(content);			return result; // 加密		} catch (NoSuchAlgorithmException e) {			e.printStackTrace();		} catch (NoSuchPaddingException e) {			e.printStackTrace();		} catch (InvalidKeyException e) {			e.printStackTrace();		} catch (IllegalBlockSizeException e) {			e.printStackTrace();		} catch (BadPaddingException e) {			e.printStackTrace();		}		return null;	}	public static void main(String[] args) {		String sKey = "adsasafq";		String str = "Hello World";		byte[] aesEncryptStr = AESEncrypt.encrypt(sKey, str);		byte[] aesDecryptStr = AESEncrypt.decrypt(sKey, aesEncryptStr);		System.out.println(new String(aesDecryptStr));	}
Sha加密-(Secure Hash Algorithm),与MD5算法类似,但复杂度要高出32个量级,不对称加密,加密过程不可逆,其中SHA-1-224-256-384-512加密复杂度依次增加,

/**	 * 散列算法	 * 	 * @param byteSource	 *            需要散列计算的数据	 * @return 经过散列计算的数据	 * @throws Exception	 */	public static String getShaStr(byte[] byteSource) {		try {			MessageDigest currentAlgorithm = MessageDigest.getInstance("SHA-256");			currentAlgorithm.reset();			currentAlgorithm.update(byteSource);			return bytes2String(currentAlgorithm.digest());		} catch (Exception e) {			e.printStackTrace();		}		return null;	}	private static String bytes2String(byte[] aa) {// 将字节数组转换为字符串		String hash = "";		for (int i = 0; i < aa.length; i++) {// 循环数组			int temp;			if (aa[i] < 0) // 判断是否是负数				temp = 256 + aa[i];			else				temp = aa[i];			if (temp < 16)				hash += "0";			hash += Integer.toString(temp, 16);// 转换为16进		}		hash = hash.toUpperCase(); // 转换为大写		return hash;	}	public static void main(String[] args) {		String str = "Hello World";		String shaEncryptStr = ShaEncrypt.getShaStr(str.getBytes());		System.out.println(shaEncryptStr);// sha1-0A4D55A8D778E5022FAB701977C5D840BBC486D0		System.out.println(shaEncryptStr.length());	}

RSA加密(三位发明者名字首字母),由一个公钥和一个私钥组成,支付宝目前就采用这种加密方式,C端持有公钥,S端持有私钥,C端发送的加密数据只能由S端来处理,安全系统业界称为最高;原理是对两大素数的乘积做拆分,有无数种可能,所以只要公钥和私钥不泄密,一般就没有问题。非对称加密,但加密过程可逆。

根证书主要从VeriSign和GlobalSign两种,就是说默认得信任,否则就互联网没有信任基础了。

详见:第9条

先简单介绍这几种,DES、AES对称加密,MD5、SHA(前两种又属于Hash算法)和RSA非对称加密。

有兴趣下载源码的请点击,!

分块隐藏ECB和CBC

ECB:直接分块加密

for(int i=0;i
width;i++) for(int j=0;j
height;j++) grey->imageData[j*grey->width+i]=bitrev(grey->imageData[j*grey->width+i]); cvNamedWindow("ecb"); cvShowImage("ecb", grey);
CBC:与上块密文异或后加密,需要向量
for(int i=0;i
width;i++) for(int j=0;j
height;j++) if(i!=0&&j!=0) grey->imageData[j*grey->width+i]=bitrev(grey->imageData[j*grey->width+i]^grey->imageData[j*grey->width+i-1]); else grey->imageData[0]=grey->imageData[0]^IV; cvNamedWindow("cbc"); cvShowImage("cbc", grey);

了解更多:

推荐一下PHP、IOS和Android都能使用的加密方法:

转载于:https://www.cnblogs.com/fengju/p/6174397.html

你可能感兴趣的文章
Python调用(运行)外部程序
查看>>
C#实体类对象修改日志记录
查看>>
Java设计模式の装饰者模式
查看>>
Facebook内部高效工作PPT指南
查看>>
BZOJ 1088 [SCOI2005]扫雷Mine
查看>>
502 Bad Gateway nginx/1.12.2 tomcat
查看>>
读取 appsettings.json
查看>>
Sicily 1150 简单魔方
查看>>
Exchange Server 2010邮件策略与遵从性
查看>>
【转】zigbee术语
查看>>
Model Binding is not working. MVC3 视图模型绑定不成功
查看>>
babel 的总结和理解
查看>>
Linux - 信息收集
查看>>
spring---aop(8)---Spring AOP中optimize
查看>>
stm32正点原子学习笔记(7-9)
查看>>
MSDN Windows XP Professional x64 Edition with SP2 +VL简体中文语言包+序列号
查看>>
如何复制百度文库中的文章
查看>>
python 获取列表大于指定长度的元素
查看>>
虚析构函数
查看>>
Oralce增加logfile(转贴)
查看>>