一、概述
cryptosystem密碼學系統分為私鑰系統及公鑰系統。
私鑰系統:指加解密雙方事先做了私有信息約定,采用對稱密鑰算法;
公鑰系統:指發送方用公開憑證對數據進行加密后傳輸,接收方使用私有憑證進行解密,采用非對稱密鑰算法;
對稱加密分類
流加密(stream cipher),加密和解密雙方使用相同偽隨機加密數據流,一般都是逐位異或或者隨機置換數據內容,常見的流加密算法如RC4。
分組加密加密(block cipher),也叫塊加密,將明文分成多個等長的模塊(block),使用確定的算法和對稱密鑰對每組分別加密解密。
高級的分組加密建立以迭代的方式產生密文,每輪產生的密文都使用不同的子密鑰,而子密鑰生成自原始密鑰。
數據加密中分組方式成為分組模式,如ECB;當加密中數據長度不足以滿足分組時需要進行填充,此時采用的方式對應填充算法,如PKCS5Padding。
二、對稱密鑰算法
DES
Data Encryption Standard,數據加密標准,由IBM研究設計。
密鑰長度8字節,有效位56bit;其中,分組為64bit=8字節。
3DES
DES像 AES過渡的加密標准。
由3個64bit的DES密鑰對數據進行三次加密。
密鑰長度為24字節,有效位168bit。
AES
Advanced Encryption Standard,高級加密標准。
包括AES-128;AES-192;AES-256算法,分組大小為128bit=16字節。
三、密碼分組模式
1 ECB
Electronic Code Book,電碼本模式
相同分組輸出相同的密鑰,簡單且利於並行運算,但無法隱藏模式,也容易招致攻擊
2 CBC
Cipher Block Chaining,密文分組鏈模式
需要初始化向量IV(長度與分組大小相同),第一組的密文與第二組數據XOR計算后再進行加密產生第二組密文
安全性較好,TLS、IPSec等標准的推薦模式,但不利於並行運算
3 CFB
Cipher Feedback,密文反饋模式
4 OFB
Output Feedback (OFB),輸出反饋模式
三、填充算法
1 NoPadding,無填充算法,通常要求數據滿足分組長度要求;
2 ZerosPadding,全部填充為0;
3 PKCS5Padding,填充字節數;
4 others…
DES像 AES過渡的加密標准
由3個64bit的DES密鑰對數據進行三次加密
密鑰長度為24字節,有效位168bit
四、代碼示例
/** * 加密工具類 * * <pre> * AES支持128/192/256,取決於密鑰長度(與位數對應) * DES密鑰長度8字節 * 3DES密鑰長度24字節 * * 采用CBC 需指定初始向量IV,長度與分組大小相同 * DES為8字節;AES為16字節 * * </pre> */
public class Crypto { static { // add bouncycastle support for md4 etc..
Security.addProvider(new BouncyCastleProvider()); } public static enum CryptType { DES_ECB_PKCS5("DES/ECB/PKCS5Padding"), DES_CBC_PKCS5("DES/CBC/PKCS5Padding", 8), DESede_ECB_PKCS5("DESede/ECB/PKCS5Padding"), DESede_CBC_PKCS5("DESede/CBC/PKCS5Padding", 8), AES_ECB_PKCS5("AES/CBC/PKCS5Padding", 16), AES_CBC_PKCS5("AES/CBC/PKCS5Padding", 16), AES_CBC_PKCS7("AES/CBC/PKCS7Padding", 16); public final String algorithm; public final String keyAlg; public final int ivlen; private CryptType(String algorithm, int ivlen) { this.algorithm = algorithm; this.keyAlg = this.algorithm.substring(0, this.algorithm.indexOf('/')); this.ivlen = ivlen; } private CryptType(String algorithm) { this(algorithm, 0); } @Override public String toString() { return this.algorithm; } } /** * Initialize the key * * @param type * @return
*/
public static String initKey(CryptType type) { try { KeyGenerator generator = KeyGenerator.getInstance(type.keyAlg); SecretKey secretKey = generator.generateKey(); byte[] key = secretKey.getEncoded(); return Codec.byteToHexString(key); } catch (Exception e) { throw new RuntimeException(e); } } /** * generate default ivparam for type * * @return
*/
public static byte[] generateDefaultIv(CryptType type) { byte[] iv = new byte[type.ivlen]; for (int i = 0; i < iv.length; i++) { iv[i] = 0x01; } return iv; } /** * Encrypt the value with the encryption standard. * * @param value * raw string * @param key * in hex format * @param iv * in hex format if exist * @param type * @return result in hex format */
public static String encrypt(String value, String key, String iv, CryptType type) { byte[] dvalue; try { dvalue = value.getBytes("utf-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } byte[] dkey = Codec.hexStringToByte(key); byte[] div = null; if (iv != null && iv.length() > 0) { div = Codec.hexStringToByte(iv); } byte[] result = encrypt(dvalue, dkey, div, type); return Codec.byteToHexString(result); } /** * Encrypt the value with the encryption standard. * * <pre> * key must have the corresponding length. * * if use cbc mode which need iv param, the iv must not be null, * and iv data length is 16 for aes, 8 for des * * </pre> * * @param value * @param key * @param iv * @return
*/
public static byte[] encrypt(byte[] value, byte[] key, byte[] iv, CryptType type) { try { SecretKeySpec skeySpec = new SecretKeySpec(key, type.keyAlg); Cipher cipher = Cipher.getInstance(type.algorithm); IvParameterSpec ivparamSpec = null; if (iv != null) { ivparamSpec = new IvParameterSpec(iv); } cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivparamSpec); return cipher.doFinal(value); } catch (Exception ex) { throw new RuntimeException(ex); } } /** * Encrypt the value with the encryption standard. * * @param value * encoded data in hex format * @param key * in hex format * @param iv * in hex format if exist * @param type * @return result raw string */
public static String decrypt(String value, String key, String iv, CryptType type) { byte[] dvalue = Codec.hexStringToByte(value); byte[] dkey = Codec.hexStringToByte(key); byte[] div = null; if (iv != null && iv.length() > 0) { div = Codec.hexStringToByte(iv); } byte[] result = decrypt(dvalue, dkey, div, type); try { return new String(result, "utf-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } /** * Decrypt the value with the encryption standard. * * <pre> * key must have the corresponding length. * * if use cbc mode which need iv param, the iv must not be null, * and iv data length is 16 for aes, 8 for des * * </pre> * * @param value * @param key * @param iv * @param type * @return
*/
public static byte[] decrypt(byte[] value, byte[] key, byte[] iv, CryptType type) { try { SecretKeySpec skeySpec = new SecretKeySpec(key, type.keyAlg); Cipher cipher = Cipher.getInstance(type.algorithm); IvParameterSpec ivparamSpec = null; if (iv != null) { ivparamSpec = new IvParameterSpec(iv); } cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivparamSpec); return cipher.doFinal(value); } catch (Exception ex) { throw new RuntimeException(ex); } } }
key 長度受限問題
Exception in thread "main" java.security.InvalidKeyException: Illegal key size or default parameters
問題原因:因軟件出版政策原因,默認 jdk 環境做了限制,當AES加密密鑰大於128位時,會出現以上異常;
解決辦法:下載JCE擴展,替換至 ${java_home}/jre/lib/security
http://www.oracle.com/technetwork/java/javase/downloads/index.html
五、參考文檔:
http://m.blog.csdn.net/article/details?id=51066799
http://www.blogjava.net/amigoxie/archive/2014/07/06/415503.html