對稱加解密算法解析

1、概述

cryptosystem密碼學系統分爲私鑰系統及公鑰系統。html

私鑰系統:指加解密雙方事先作了私有信息約定,採用對稱密鑰算法; 
公鑰系統:指發送方用公開憑證對數據進行加密後傳輸,接收方使用私有憑證進行解密,採用非對稱密鑰算法;java

對稱加密分類

流加密(stream cipher),加密和解密雙方使用相同僞隨機加密數據流,通常都是逐位異或或者隨機置換數據內容,常見的流加密算法如RC4。 
分組加密加密(block cipher),也叫塊加密,將明文分紅多個等長的模塊(block),使用肯定的算法和對稱密鑰對每組分別加密解密。 
高級的分組加密創建以迭代的方式產生密文,每輪產生的密文都使用不一樣的子密鑰,而子密鑰生成自原始密鑰。 
數據加密中分組方式成爲分組模式,如ECB;當加密中數據長度不足以知足分組時須要進行填充,此時採用的方式對應填充算法,如PKCS5Padding。算法

2、對稱密鑰算法

DES

Data Encryption Standard,數據加密標準,由IBM研究設計。 
密鑰長度8字節,有效位56bit;其中,分組爲64bit=8字節。安全

3DES

DES像 AES過渡的加密標準。 
由3個64bit的DES密鑰對數據進行三次加密。 
密鑰長度爲24字節,有效位168bit。oracle

AES

Advanced Encryption Standard,高級加密標準。 
包括AES-128;AES-192;AES-256算法,分組大小爲128bit=16字節。ide

3、密碼分組模式

1 ECB

Electronic Code Book,電碼本模式 
相同分組輸出相同的密鑰,簡單且利於並行運算,但沒法隱藏模式,也容易招致攻擊工具

2 CBC

Cipher Block Chaining,密文分組鏈模式 
須要初始化向量IV(長度與分組大小相同),第一組的密文與第二組數據XOR計算後再進行加密產生第二組密文 
安全性較好,TLS、IPSec等標準的推薦模式,但不利於並行運算this

3 CFB

Cipher Feedback,密文反饋模式 
加密

4 OFB

Output Feedback (OFB),輸出反饋模式 
spa

3、填充算法

1 NoPadding,無填充算法,一般要求數據知足分組長度要求; 
2 ZerosPadding,所有填充爲0; 
3 PKCS5Padding,填充字節數; 
4 others…

DES像 AES過渡的加密標準 
由3個64bit的DES密鑰對數據進行三次加密 
密鑰長度爲24字節,有效位168bit

 

4、代碼示例

/** * 加密工具類 * * <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

5、參考文檔:

http://m.blog.csdn.net/article/details?id=51066799 
http://www.blogjava.net/amigoxie/archive/2014/07/06/415503.html

相關文章
相關標籤/搜索