【Java编码准则】の #12不要使用不安全或者强度弱的加密算法

     安全性要求高的应用程序必须避免使用不安全的或者强度弱的加密算法,现代计算机的计算能力使得攻击者通过暴力破解能够攻破强度弱的算法。比如,数据加密标准算法DES是极度不安全的,使用类似EFF(Electronic Frontier Foundaton) Deep Crack的计算机在一天内能够暴力破解由DES加密的消息。


[不符合安全要求的代码演示样例]

     以下的代码使用强度弱的DES算法对字符串进行加密:

	SecretKey key = KeyGenerator.getInstance("DES").generateKey(); 
	Cipher cipher = Cipher.getInstance("DES"); 
	cipher.init(Cipher.ENCRYPT_MODE, key);
	
	// encode bytes as UTF8; strToBeEncrypted contains
	// the input string that is to be encrypted
	byte[] encoded = strToBeEncrypted.getBytes("UTF-8");
	
	// perform encryption
	byte[] encrypted = cipher.doFinal(encoded);


[符合安全要求的解决方式]

     本方案使用更加安全的AES加密算法来对字符串进行加密

	Cipher cipher = Cipher.getInstance("AES");
	KeyGenerator kgen = KeyGenerator.getInstance("AES");
	kgen.init(128);	// 192 and 256 bits may be unavailable
	
	SecretKey skey = kgen.generateKey();
	byte[] raw = skey.getEncoded();
	
	SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
	cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
	
	// encode bytes as UTF8; strToBeEncrypted contains the
	// input string that is to be encrypted
	byte[] encoded = strToBeEncrpyted.getBytes("UTF-8");
	
	// perform encryption
	byte[] encrypted = cipher.doFinal(encoded);


[可用性]

     使用数学和计算上不安全的加密算法可能导致敏感信息的泄漏。强度弱的加密算法在Java SE 7中能够去使能,它们能够被用在加密同意被破解的场景。比如,ROT13加密算法被广泛用在电子公告牌和网页,这里加密的目的是保护人们免受信息的干扰,而不是保护信息不被人们知道。


——欢迎转载,请注明出处 http://blog.csdn.net/asce1885 ,未经本人允许请勿用于商业用途,谢谢——

原文地址:https://www.cnblogs.com/mengfanrong/p/4264422.html