天天看點

【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加密算法被廣泛用在電子公告牌和網頁,這裡加密的目的是保護人們免受資訊的幹擾,而不是保護資訊不被人們知道。