0

Im trying to create an AES 256 cbc encryption using java and I need to emulate EXACTLY this javascript code (I know the iv is the same as the key (turnicated to 16 bytes), that's how it is from the site i'm trying to log into using java)

var recievedStr = "MDk4NTY1MDAyMjg2MTU1OA=="; //some 
var key =  CryptoJS.enc.Base64.parse(recievedStr);
var iv  =  CryptoJS.enc.Base64.parse(recievedStr);
var pw = "PASSWORD";

var encres = CryptoJS.AES.encrypt(pw, key, {iv:iv, keySize: 256, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7});
var finalStr = encres.toString();

finalStr will be : Su92ZXLm/MdOyruRnWDRqQ==

I need to make a java code that will output exactly the same output as finalStr from the javascript. Im using bouncy castle for that.

        String recievedStr = "MDk4NTY1MDAyMjg2MTU1OA==";
        String pw = "PASSWORD";
        AESEngine blockCipher = new AESEngine();
          CBCBlockCipher cbcCipher = new CBCBlockCipher(blockCipher);
    BufferedBlockCipher cipher = new PaddedBufferedBlockCipher (cbcCipher);
    byte[] key = encodeBase64(recievedStr);
    byte [] iv = java.util.Arrays.copyOf(key,16);
    byte[] input = pw.getBytes();
    ParametersWithIV pwIV= new ParametersWithIV(new KeyParameter(key),iv);
    cipher.init(true, pwIV);
    byte[] cipherText = new byte[cipher.getOutputSize(input.length)];
    int outputLen = cipher.processBytes(input, 0, input.length, cipherText, 0);
    try
    {
        cipher.doFinal(cipherText, outputLen);
    }
    catch (CryptoException ce)
    {
        System.err.println(ce);
        }
        System.out.println(new String(Base64.encodeBase64(cipherText)));

this will output : qEGQ1PC/QKxfAxGBIbLKpQ==

while I can decrypt it to the original input, that is not what i want. I need my java code to output exactly what the javascript did. I have 0 ideas left on how to approach this.

Thanks.

EDIT: problem was solved, I had to decode the received string to base64 instead of encoding it.

  • 1
    shouldn't it be decodeBase64(recievedStr) instead of encodeBase64(recievedStr)? – AdrianEddy Apr 06 '16 at 10:25
  • that was exactly it! thx – user1827217 Apr 06 '16 at 14:37
  • "MDk4NTY1MDAyMjg2MTU1OA==" is 16 bytes long when decoded which means that it is AES-128 and not AES-256. The `keySize` property is ignored when an actual key is provided. Nevertheless, it would be wrong, because `keySize: 256/32` would be the correct way of defining the key size. – Artjom B. Apr 06 '16 at 18:17

1 Answers1

0

I think you are on the right track. But I think you are running with AES-128 instead of AES-256. If you have a look at Java 256-bit AES Password-Based Encryption I think maybe you can find something useful.

Community
  • 1
  • 1