简体   繁体   English

CryptoJS AES和Java AES加密值不匹配

[英]CryptoJS AES and Java AES encrypted value mismatch

I am trying to encrypt in client and decrypt in sever using AES, so using cryptojs to encrypt in client side with CBC mode and nopadding in server side also using Cipher class with same mode and nopadding 我正在尝试使用AES在客户端加密和在服务器上解密,因此使用cryptojs在客户端使用CBC模式加密,在服务器端使用nopadding也使用在相同模式和nopadding下使用的Cipher

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());
}

Server side code 服务器端代码

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 ....

implementation 实作

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

Results 结果

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

Can anybody point out the mistake? 有人可以指出错误吗?

There are a few things wrong with the code: 该代码有一些错误:

  • you are using hexadecimal decoding of the key in JavaScript, and String.getBytes() - character encoding without specifying the character set - in Java 您在JavaScript中使用密钥的十六进制解码,并且在Java中使用String.getBytes() -字符编码而未指定字符集-
  • your key is 16 characters (it should be 16, 24 or 32 randomized bytes ), but it is not in hexadecimals 您的密钥为16个字符(应为16个,24个或32个随机字节 ),但不能为十六进制
  • you are encrypting instead of decrypting on the "server side", although that one is probably on purpose 您正在加密而不是在“服务器端”解密,尽管那可能是故意的

Take another good look on how to perform encoding and character-encoding, they are essential for good crypto and often performed incorrectly (it's probably the most common issue on Stackoverflow regarding encryption) 再看看如何执行编码和字符编码,它们对于良好的加密至关重要,并且经常执行不正确(这可能是Stackoverflow上最常见的加密问题)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM