0

我正在尝试使用 AES 在客户端加密并在服务器中解密,因此使用 cryptojs 在客户端以 CBC 模式进行加密,并在服务器端使用 nopadding 也使用Cipher具有相同模式和 nopadding 的类

function call()
{
  var key = CryptoJS.enc.Hex.parse('roshanmathew1989');
  var iv  = CryptoJS.enc.Hex.parse('roshanmathew1989');
  var encrypted = CryptoJS.AES.encrypt("roshanmathew1989",key,{ iv: iv},
      {padding:CryptoJS.pad.NoPadding});
  alert(encrypted.ciphertext.toString(CryptoJS.enc.Base64));
  alert(encrypted.iv.toString());
}

服务器端代码

public class Crypto
{ 

  private static byte[] key = null;

  public void setKey(String key){this.key=key.getBytes();}

  public String encrypt(String strToEncrypt)
  {
    String encryptedString =null;
    try
    {
      Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
      final SecretKeySpec secretKey = new SecretKeySpec(key,"AES");
      System.out.println("sdfsdf = "+key.toString());
      IvParameterSpec ips = new IvParameterSpec(key);
      cipher.init(Cipher.ENCRYPT_MODE, secretKey,ips);
      encryptedString = Base64.encodeBase64String(cipher.doFinal(strToEncrypt.getBytes()));
    }
    catch(Exception e)
    {
      System.out.println(" ERROR : "+e.getMessage());
    }
    return encryptedString;

  } other method omitted ....

执行

Crypto cry=new Crypto();
cry.setKey("roshanmathew1989");
String s=cry.encrypt("roshanmathew1989");

结果

Browser side value =       O64X/bKNBu7R2Tuq2lUbXeFlQ7wD2YnFasyyhsVUryw=
Server side value of s =   RrNcVIER/75fzdjHr884sw==

任何人都可以指出错误吗?

4

1 回答 1

0

代码有几个问题:

  • 您在 JavaScript 中使用密钥的十六进制解码,并且String.getBytes()- 在 Java 中未指定字符集的字符编码
  • 您的密钥是 16 个字符(应该是 16、24 或 32 个随机字节),但不是十六进制
  • 您正在加密而不是在“服务器端”解密,尽管那个可能是故意的

再好好看看如何执行编码和字符编码,它们对于良好的加密至关重要并且经常执行不正确(这可能是 Stackoverflow 上关于加密的最常见问题)

于 2013-05-19T00:20:16.493 回答