openresty / lua-resty-string

String utilities and common hash functions for ngx_lua and LuaJIT
429 stars 143 forks source link

Unable to decrypt cipher encrypted by Crypto-JS (AES default) #62

Open prakharmishra opened 6 years ago

prakharmishra commented 6 years ago

Hello, I am not able to decrypt back what was encrypted using Crypto-JS in browser Javascript / NodeJS:

// Encrypt
var ciphertext = CryptoJS.AES.encrypt('testingtestingtestingtestingtestingtestingtestingtestingtestingtestingtestingtestingtestingtestingtestingtestingtestingtestingtestingtestingtestingtestingtestingtestingtestingtestingtestingtestingtestingtestingtestingtestingtestingtestingtestingtestingtestingtestingtestingtesting', '&&nH8P3bxk+?C4gR');

// Decrypt
var bytes  = CryptoJS.AES.decrypt(ciphertext.toString(), '&&nH8P3bxk+?C4gR');
var plaintext = bytes.toString(CryptoJS.enc.Utf8);

console.log(plaintext);

I can decrypt it in Java using: Cipher.getInstance("AES/CBC/PKCS5Padding") But, I get nil when I try to do it with resty.aes. Here is the code:

local aes = require "resty.aes"
local cipher = aes.cipher(256)
local aes_256_cbc_md5 = aes:new('&&nH8P3bxk+?C4gR', nil, cipher)

local cipherText = 'U2FsdGVkX1859eIyt4M7VHNBl9BGMdsemPYAADKmqs9sltwKINfzVMci0Vw1NLr73Iti67zQ0+JoqVcL59Gcp+4R5NY6wg2n3r0wqLcQRc7PkIGpgup1UJp4DzhXSIGHz08Eu/nEbt3jAh3S4GVUoVFbXLluf/BvedTGdsqcN2EPL9S/WQOc5QDyl9OQjpBl+QS56nWL0DO6iR/6CIoEuQ+zC/7KTpBw2jQf8sxuDNptZzwKLlDi2sWSaeCkvPj+m8zheAlnZzVc+L5JeLdcx7WkIRQImNs9P5bkhXmiK2nZnw4yco3QHbzRkRBJiB3HgdYDauHsuKmR21zv9VLjAcGTrZjiUbtrBfuTRawKOiAFm599Inbq+Ugu9n4RelQ2CTdxwDfe3ZE3kscP3dyAmg=='
ngx.say(aes_256_cbc_md5:decrypt(cipherText))

Could someone please help me with server side decryption?

Rulexec commented 5 years ago

Same issue. I added logging here:

if C.EVP_DecryptFinal_ex(ctx, buf + out_len[0], tmp_len) == 0 then 
    ngx.log(ngx.STDERR, "aes3: " .. inspect(ffi_str(buf, 32))) 
    return nil 
end 

And looks like buf contains decrypted text, but somewhy it returns 0.

OpenSSL says, that:

EVP_DecryptFinal() will return an error code if padding is enabled and the final block is not correctly formatted.

My issue was resolved with disabling padding:

local C = ffi.C
ffi.cdef[[
typedef struct evp_cipher_ctx_st EVP_CIPHER_CTX;

int EVP_CIPHER_CTX_set_padding(EVP_CIPHER_CTX *ctx, int pad);
]]

-- ...

C.EVP_CIPHER_CTX_set_padding(encryptor._decrypt_ctx, 0)

There should be an API for #67

shuxiao9058 commented 3 years ago

the same issue