Search code examples
javaluaaesopenresty

The AES encryption results calculated by Lua and Java are inconsistent


Background: java has a set of ready-made code, which needs to be migrated to lua now.

When testing: the same key is used

key = "1938703285589872452";

data = "111111";

1.java's encryption code

pom

    <dependency>
        <groupId>org.bouncycastle</groupId>
        <artifactId>bcprov-jdk15on</artifactId>
        <version>1.55</version>
    </dependency>

    <dependency>
        <groupId>org.bouncycastle</groupId>
        <artifactId>bcpkix-jdk15on</artifactId>
        <version>1.55</version>
    </dependency>

    <dependency>
        <groupId>commons-codec</groupId>
        <artifactId>commons-codec</artifactId>
        <version>1.10</version>
    </dependency>

code

import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.crypto.engines.AESEngine;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.crypto.paddings.PKCS7Padding;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

// ... 

// 加密方法
    public static String encryptWithBC(String data, String key) throws Exception {
        // key
        ByteBuffer keyBuffer = ByteBuffer.allocate(32);
        keyBuffer.put(key.getBytes());
        KeyParameter keyParameter = new KeyParameter(keyBuffer.array());
        // 请求数据
        byte[] dataByteArr = data.getBytes(StandardCharsets.UTF_8);

        // init
        CBCBlockCipher aes = new CBCBlockCipher(new AESEngine());
        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(aes, new PKCS7Padding());
        cipher.init(true, keyParameter);

        byte[] output = new byte[cipher.getOutputSize(dataByteArr.length)];
        int len = cipher.processBytes(dataByteArr, 0, dataByteArr.length, output, 0);
        cipher.doFinal(output, len);

        return Base64.encodeBase64String(output);
    }

2.lua's encryption code

-- AES加密
local aes = require "resty.aes"

-- ...

-- 加密方法
function _M.encrypt_128_cbc_pkcs7(en_data, aes_key)
    --local aes_256_cbc_with_padding = aes:new(key, nil, aes.cipher(256,"cbc"), {iv = string.sub(key, 1, 16)}, nil, nil, enable_padding)
    local aes_128_cbc_pkcs7 = aes:new(aes_key, nil, aes.cipher(128, "cbc"), nil, nil, nil, "PKCS7")
    local encrypted = aes_128_cbc_pkcs7:encrypt(en_data)
    -- 转base64
    local encrypted_base64 = wkg_hex_utils.str_to_base64(encrypted)
    local encrypted_hex = wkg_hex_utils.base64_to_hex(encrypted_base64)


    wkg_log_utils.log("AES加密结果(BASE64): {}", encrypted_base64)
    wkg_log_utils.log("AES加密结果(Hex): {}", encrypted_hex)
    return encrypted_base64
end

Lua is a reference git:https://github.com/openresty/lua-resty-string

I can only see the information of cbc and pkcs7Padding, but now the result values are completely wrong.

Results of lua:

111111
X32vI7ROqoK3hjQ9fvrOKg==
5F7DAF23B44EAA82B786343D7EFACE2A

Results of java:

111111
dA8O3S8ApkzypCudVFj5ZA==
740F0EDD2F00A64CF2A42B9D5458F964

The treatment of base64 in both languages is similar.

java:

    public static String base64ToHex(String base64Str) {
        byte[] decode = Base64.decode(base64Str);
        return byteArrToHex(decode).toUpperCase(Locale.ROOT);
    }

lua:

    function wkg_hex_utils.base64_to_hex(base64_str)
    local temp = ngx.decode_base64(base64_str)
    wkg_log_utils.log("base64解码类型: {},值: {}", type(temp), temp)
            return wkg_hex_utils.str_to_hex(temp)
    end

There is no direction. I hope you can give me some guidance. Thank you.


Now I'm trying to convert the encrypted result into byteArr. They are like this.

java:

[116, 15, 14, -35, 47, 0, -90, 76, -14, -92, 43, -99, 84, 88, -7, 100]

lua:

[95, 125, 175, 35, 180, 78, 170, 130, 183, 134, 52, 61, 126, 250, 206, 42]

Can someone help me answer it? thanks


Solution

  • First I want to tell you that what you did in Java is AES-256-CBC encryption with PKCS7 padding. The number 256 is the key length in bits, which means 32 bytes as you used in Java code.

    local aes = require "resty.aes"
    local str = require "resty.string"
    local key = '1938703285589872452'
    
    local aes_java = aes:new(key .. string.rep('\0', 32-#key), nil,
      aes.cipher(256,"cbc"), { iv = '\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0' })
    ngx.say(str.to_hex(aes_java:encrypt('111111')))
    -- output: 740f0edd2f00a64cf2a42b9d5458f964
    

    As your key is shorter than required 32 bytes, we need to append zeros to get the real key used in AES-256-CBC encryption. One more thing, the iv vector has to be specified to achieve PKCS7 padding. In Java, I think PaddedBufferedBlockCipher generates the default iv vector for you, but for Lua, you have to pass the default iv vector to aes:new.