2017-06-01 233 views
0

我使用PBEWithMD5AndDES算法來加密/解密java中的一個字符串。如何在JavaScript中實現PBEWithMD5AndDES算法?

public static String encrypt(String originalPassword) throws Exception { 
    String methodName = "encrypt -->"; 
    _logger.debug(methodName + Constants.CALLED); 
    String encryptedString = null; 
    try { 
     SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); 
     SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD)); 
     Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES"); 
     pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(SALT, 20)); 
     encryptedString = base64Encode(pbeCipher.doFinal(originalPassword.getBytes("UTF-8"))); 
     _logger.debug(methodName + "encrypted string " + encryptedString); 
    } catch (Exception e) { 
     _logger.error(methodName + "Encryption failed due to: " + e.getMessage()); 
     throw new Exception("Failed to Encrypt String"); 
    } 
    _logger.debug(methodName + Constants.END); 
    return encryptedString; 
} 

public static String decrypt(String encryptedPassword) throws Exception { 
     String methodName = "decrypt -->"; 
     _logger.debug(methodName + Constants.CALLED); 
     String decryptedString = null; 
     try { 
      _logger.debug(methodName + " string to decrypt " + encryptedPassword); 
      SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); 
      SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD)); 
      Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES"); 
      pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(SALT, 20)); 
      decryptedString = new String(pbeCipher.doFinal(base64Decode(encryptedPassword)), "UTF-8"); 
     } catch (Exception e) { 
      _logger.error(methodName + "Decryption failed due to: " + e.getMessage()); 
      throw new Exception("Failed to Decrypt String"); 
     } 
     _logger.debug(methodName + Constants.END); 
     return decryptedString; 
    } 

我已經爲此算法定義了我自己的salt。但我想從JavaScript加密一些字符串。

我們可以在JavaScript中實現相同的算法(PBEWithMD5AndDES)嗎?

回答

1

您可以使用CryptoJS這個 這裏是URL https://github.com/sytelus/CryptoJS

+0

非常感謝Mantu。 JS中的PBEWithMD5AndDES不可能實現加密嗎? –

+1

這裏是工作小提琴的網址http://fiddle.jshell.net/artjomb/Lpbo7yrb/ –

+0

我真的很感激你的回覆,但我想知道,我們可以用PBEWithMD5AndDES做同樣的事情嗎?如果沒有,那麼我會在前端添加CryptoJS代碼,並且相應地更改我的Java代碼。 –