Louis Q
Louis Q

Reputation: 176

AES ECB No padding

I am trying to implement AES/ECB/NoPadding with cryptojs.

On the Java side I have this:

public static String encrypt(String input, String key) throws Exception {
    SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(), "AES");
    Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    return DatatypeConverter.printHexBinary(cipher.doFinal(padToMultipleOf32(input.getBytes())));
}

public static byte[] padToMultipleOf32(final byte[] bytes) {
    int n16 = ((bytes.length + 31) / 32);
    int paddedLen = n16 * 32;

    byte[] result = new byte[paddedLen];

    for (int i = 0; i < bytes.length; i++) {
        result[i] = bytes[i];
    }

    for (int i = bytes.length; i < paddedLen; i++) {
        result[i] = 0x00;
    }

    System.out.println(new String(result).length());

    return result;
}

Running Test.encrypt("test", "4g2ef21zmmmhe678") Gives me: C24F53DDEAD357510A27AA283C74BBF4638B3F81F8EB44652D424D7C32897525

How would I do the same in cryptojs, what I have currently doesnt work:

var pwd = CryptoJS.AES.encrypt("test", "4g2ef21zmmmhe678", {
        mode : CryptoJS.mode.ECB,
        padding : CryptoJS.pad.NoPadding
    });
    expect(pwd.ciphertext.toString(CryptoJS.enc.Base64)).toEqual("C24F53DDEAD357510A27AA283C74BBF4638B3F81F8EB44652D424D7C32897525");

Please help

Upvotes: 0

Views: 4838

Answers (1)

i_turo
i_turo

Reputation: 2729

The documentation of CryptoJS says that when passing a plain passphrase (i.e. a String) to encrypt () , it will automatically generate a 256 bit key (Java implements the 128 bit version) using that password as the seed.

To prevent that you can use this function to directly convert your passphrase to a key:

var key = CryptoJS.enc.Utf8.parse("password");

Possibly you will also have to synchronize the encodings of the ciphertexts. See here for a detailed example on how to perform interoperable encryption with Java and CryptoJS.

Upvotes: 1

Related Questions