简体   繁体   中英

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

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
  • your key is 16 characters (it should be 16, 24 or 32 randomized bytes ), but it is not in hexadecimals
  • 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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