Encrypt a string in nodejs and decrypt in java - node.js

I am encrypting a text in NODEJS and trying decrypt in Java but getting error.
my nodejs code:
var crypto = require('crypto')
, key = 'mykey#91'
, plaintext = 'SS18617710213463'
, cipher = crypto.createCipher('aes-128-ecb', key)
, decipher = crypto.createDecipher('aes-128-ecb', key);
var encryptedPassword = cipher.update(plaintext, 'utf8', 'base64');
encryptedPassword += cipher.final('base64')
var decryptedPassword = decipher.update(encryptedPassword, 'base64', 'utf8');
decryptedPassword += decipher.final('utf8');
console.log('original :', plaintext);
console.log('encrypted :', encryptedPassword);
console.log('decrypted :', decryptedPassword);
but when I am trying to decrypt it, it always throws an error.
public static String decrypt(String encryptedText) {
try {
final String key = "mykey#91";
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] cipherText = Base64.getDecoder().decode(encryptedText.getBytes("UTF8"));
String decryptedString = new String(cipher.doFinal(cipherText),"UTF8");
return decryptedString;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
The error I am getting as below:
java.security.InvalidKeyException: Invalid AES key length: 8 bytes

The reason you are getting Invalid AES key length: 8 bytes invalid AES is related to length of your key and text. You need to make sure that its length in bits is a power of two. If you want to use a String as your encryption key, check its length in bytes and multiply by 8 to find the length in bits. Also most String implementation will require 2 bytes for every character (Java 64bit). Detailed information here: How to solve InvalidKeyException
In this case, the mentioned error will disappear just using a padded or longer key, for example:
static String PLAIN_TEXT = "SS18617710213463";
static String ENCRYPTION_KEY = "mykey#91mykey#91";
However there is another important thing to consider. The Java Implementation has to match the exact algorithms provided by node.js. This is not as easy as it sounds (at least based on my experience). In your case, I would suggest you to use node-forge on node.js side which is easier to match Java implementations:
var forge = require('node-forge');
var plaintext = 'SS18617710213463';
var key = 'mykey#91mykey#91';
var iv = 'AODVNUASDNVVAOVF';
console.log('Plain Text: ' + plaintext);
var cipher = forge.cipher.createCipher('AES-CBC', key);
cipher.start({iv: iv});
cipher.update(forge.util.createBuffer(plaintext));
cipher.finish();
var encrypted = cipher.output;
var encodedB64 = forge.util.encode64(encrypted.data);
console.log("Encoded: " + encodedB64);
var decodedB64 = forge.util.decode64(encodedB64);
encrypted.data = decodedB64;
var decipher = forge.cipher.createDecipher('AES-CBC', key);
decipher.start({iv: iv});
decipher.update(encrypted);
var result = decipher.finish();
console.log("Decoded: " + decipher.output.data);
Running the code above, the output should be:
Plain Text: SS18617710213463
Encoded: HCzZD7uc13fqfM6odWcXf/mdR4aNJfkMDhEbnU+asjE=
Decoded: SS18617710213463
And the compatible Java code that will work on the same way looks like the code below:
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class Main {
static String PLAIN_TEXT = "SS18617710213463";
static String ENCRYPTION_KEY = "mykey#91mykey#91";
static String INITIALIZATIO_VECTOR = "AODVNUASDNVVAOVF";
public static void main(String [] args) {
try {
System.out.println("Plain text: " + PLAIN_TEXT);
byte[] encryptedMsg = encrypt(PLAIN_TEXT, ENCRYPTION_KEY);
String base64Encrypted = Base64.getEncoder().encodeToString(encryptedMsg);
System.out.println("Encrypted: "+ base64Encrypted);
byte[] base64Decrypted = Base64.getDecoder().decode(base64Encrypted);
String decryptedMsg = decrypt(base64Decrypted, ENCRYPTION_KEY);
System.out.println("Decrypted: " + decryptedMsg);
} catch (Exception e) {
e.printStackTrace();
}
}
public static byte[] encrypt(String plainText, String encryptionKey) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/pkcs5padding", "SunJCE");
SecretKeySpec key = new SecretKeySpec(encryptionKey.getBytes("UTF-8"), "AES");
cipher.init(Cipher.ENCRYPT_MODE, key,new IvParameterSpec(INITIALIZATIO_VECTOR.getBytes("UTF-8")));
return cipher.doFinal(plainText.getBytes("UTF-8"));
}
public static String decrypt(byte[] cipherText, String encryptionKey) throws Exception{
Cipher cipher = Cipher.getInstance("AES/CBC/pkcs5padding", "SunJCE");
SecretKeySpec key = new SecretKeySpec(encryptionKey.getBytes("UTF-8"), "AES");
cipher.init(Cipher.DECRYPT_MODE, key,new IvParameterSpec(INITIALIZATIO_VECTOR.getBytes("UTF-8")));
return new String(cipher.doFinal(cipherText),"UTF-8");
}
}
Which produces:
Plain text: SS18617710213463
Encrypted: HCzZD7uc13fqfM6odWcXf/mdR4aNJfkMDhEbnU+asjE=
Decrypted: SS18617710213463

Related

AES/GCM/NoPadding in swift iOS

I want to implement AES GCM encryption/decryption using shared secret.
But Backend server is throwing error with my keys. This is working fine in Android app with Java. Although size of encrypted text is same in both iOS and Android.
My iOS code.
private func getCryptoPublicKey() -> (privateKey: Curve25519.KeyAgreement.PrivateKey,publicKey :Curve25519.KeyAgreement.PublicKey){
let ephemeralKey = Curve25519.KeyAgreement.PrivateKey()
//AES.KeyWrap.wrap(SymmetricKey(size: .bits256), using: <#T##SymmetricKey#>)
let ephemeralPublicKey = ephemeralKey.publicKey
let privateKey = ephemeralKey.rawRepresentation.base64EncodedString()
let publicKey = ephemeralPublicKey.rawRepresentation.base64EncodedString()
Singleton.shared.clientPrivateKey = privateKey
Singleton.shared.clientPublicKey = publicKey
return (ephemeralKey,ephemeralPublicKey)
}
let cryptoData = self.getCryptoPublicKey()
let publicKeyData = Data.init(base64Encoded: ServerPublicKey)! //ServerPublicKey is shared by server
let serverPublicKey = try! Curve25519.KeyAgreement.PublicKey(rawRepresentation: publicKeyData)
let clientSharedSecret = try! cryptoData.privateKey.sharedSecretFromKeyAgreement(with: serverPublicKey)
let clientSharedSecretSymmetricKey = clientSharedSecret.x963DerivedSymmetricKey(using: SHA256.self, sharedInfo: Data(), outputByteCount: 32)
let clientSealedBoxDatakClientId = try! AES.GCM.seal(kClientId.data(using: .utf8)!, using: clientSharedSecretSymmetricKey).combined!
let clientSealedBoxDatakClientSecret = try! AES.GCM.seal(kClientSecret.data(using: .utf8)!, using: clientSharedSecretSymmetricKey).combined!
let clientSealedBoxDataCredent = try! AES.GCM.seal("client_credentials".data(using: .utf8)!, using: clientSharedSecretSymmetricKey).combined!
let clientIDEncryptedBase64Str = clientSealedBoxDatakClientId.base64EncodedString()
let clientSecretEncryptedBase64Str = clientSealedBoxDatakClientSecret.base64EncodedString()
let clientCredentialsEncryptedBase64Str = clientSealedBoxDataCredent.base64EncodedString()
JAVA CODE:
`
private void makeKeyExchangeParams() {
KeyPairGenerator kpg;
try {
kpg = KeyPairGenerator.getInstance("X25519", new org.bouncycastle.jce.provider.BouncyCastleProvider());
kpg.initialize(AES_KEY_SIZE);
KeyPair kp = kpg.generateKeyPair();
publickey = kp.getPublic();
keyAgreement = KeyAgreement.getInstance("XDH", new org.bouncycastle.jce.provider.BouncyCastleProvider());
keyAgreement.init(kp.getPrivate());
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
e.printStackTrace();
}
}
package com.bankofbaroda.bobabhivyakti.Utilities.Encryption;
import android.os.Build;
import androidx.annotation.RequiresApi;
import javax.crypto.*;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.util.Base64;
public class CryptoService {
public static final int GCM_IV_LENGTH = 12;
public static final int GCM_TAG_LENGTH = 16;
#RequiresApi(api = Build.VERSION_CODES.O)
public static String getEncryptedText(String plainText, SecretKey secretKey) {
if(plainText == null) {
plainText = "";
}
try {
byte[] ivBytes = new byte[GCM_IV_LENGTH];
SecureRandom random = new SecureRandom();
random.nextBytes(ivBytes);
String iv = Base64.getEncoder().encodeToString(ivBytes);
byte[] cipherText = encrypt(plainText.getBytes(), secretKey, ivBytes);
String text = Base64.getEncoder().encodeToString(cipherText);
text = iv+text;
return text;
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
#RequiresApi(api = Build.VERSION_CODES.O)
public static String getDecryptedText(String cipherText, SecretKey secretKey) {
try {
String iv = cipherText.substring(0,16);
byte[] ivBytes = Base64.getDecoder().decode(iv);
cipherText = cipherText.substring(16);
byte[] data = Base64.getDecoder().decode(cipherText);
return decrypt(data, secretKey, ivBytes);
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
private static byte[] encrypt(byte[] plaintext, SecretKey key, byte[] nonce) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), "AES");
GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, nonce);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, gcmParameterSpec);
return cipher.doFinal(plaintext);
}
private static String decrypt(byte[] cipherText, SecretKey key, byte[] nonce) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), "AES");
GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, nonce);
cipher.init(Cipher.DECRYPT_MODE, keySpec, gcmParameterSpec);
byte[] decryptedText = cipher.doFinal(cipherText);
return new String(decryptedText);
}
}
`
I am not able to get what is exact issue here. Do I have to change something on Java side?

Java to Node.js AES/ECB/PKCS5Padding Encryption

I have the following encrypt function in JAVA. I am trying to write the same encryption in Node.js using cipher from crypto. But, the output is not the same. It is using the same key and input.
JAVA
public static String encrypt(String input, String key) {
byte[] crypted = null;
try {
SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skey);
crypted = cipher.doFinal(input.getBytes());
} catch (Exception e) {
System.out.println(e.toString());
}
String result = new String(Base64.encodeBase64(crypted));
return result.replace("+", "-");
}
Sample output: 0HCkcjWj/PoCZ4ZUFJARs/m4kstigMFk8dQnT0uNhog= (44 characters)
Node.js
encrypt = (input, key) => {
const algorithm = 'aes-128-cbc';
key = crypto.scryptSync(key, 'salt', 16);
const iv = Buffer.alloc(16, 0);
const cipher = crypto.createCipheriv(algorithm, key, iv);
cipher.setAutoPadding(true);
let encrypted = cipher.update(input, 'utf8', 'base64');
encrypted += cipher.final('base64');
return encrypted.replace('+','-');
}
Sample output: ZHtEbAhrIo7vWOjdMNgW6Q== (24 characters)
Thanks in advance.
So that the NodeJS code is functionally identical to the Java code, in the NodeJS code:
ECB mode must be used instead of CBC mode:
const algorithm = 'aes-128-ecb';
...
//const iv = Buffer.alloc(16, 0); // remove
const cipher = crypto.createCipheriv(algorithm, key, null);
Note, however, that ECB doesn't use an IV, is generally insecure and should therefore not be used, [1].
Better alternatives are CBC mode (confidentiality) or GCM mode (confidentiality, authenticity/integrity), [2], [3].
No key derivation function may be applied [4], i.e. the following line must be removed:
key = crypto.scryptSync(key, 'salt', 16);

padding is invalid and cannot be removed decrypt value

Hello I want to encrypt and Decrypt Text . My encrypt code is working fine and matching the value that i want. But when i want Decrypt this is giving error padding is invalid and cannot be removed . In below code first i am giving my Encrypt and Decrypt both code. Also i have to fix this error Stack overflow link, StackoverlFlow Link 2 but not fix it .
string getHashKey1 = EncryptText("10002:1486703720424", "hpIw4SgN)TxJdoQj=GKo)p83$uHePgoF");
Result = 1ltQFLRGNif73uCNzi0YEvBqLKiRgx6fWsk5e/GcTQc=
string reverseKey = DecryptText('1ltQFLRGNif73uCNzi0YEvBqLKiRgx6fWsk5e/GcTQc=', "hpIw4SgN)TxJdoQj=GKo)p83$uHePgoF");
When i add in AES_Decrypt aes.Padding = PaddingMode.Zeros; i get below result.
Result : -����y�7�t���Ij���,���� Z��$�
public string EncryptText(string input, string password)
{
string result = "";
try
{
// Get the bytes of the string
byte[] bytesToBeEncrypted = Encoding.UTF8.GetBytes(input);
byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
byte[] bytesEncrypted = AES_Encrypt(bytesToBeEncrypted, passwordBytes);
result = Convert.ToBase64String(bytesEncrypted);
return result;
}
catch (Exception ex)
{
}
return result;
}
public byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes)
{
byte[] encryptedBytes = null;
try
{
using (MemoryStream ms = new MemoryStream())
{
using (Aes aes = Aes.Create())
{
aes.Key = passwordBytes;
aes.Mode = CipherMode.ECB;
// "zero" IV
aes.IV = new byte[16];
using (var cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
cs.Close();
}
encryptedBytes = ms.ToArray();
}
}
}
catch (Exception ex)
{
}
return encryptedBytes;
}
Above code is working fine for encrypt .
Below code is giving error
padding is invalid and cannot be removed
public string DecryptText(string input, string password)
{
// Get the bytes of the string
byte[] bytesToBeDecrypted = Convert.FromBase64String(input);
byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
passwordBytes = SHA256.Create().ComputeHash(passwordBytes);
byte[] bytesDecrypted = AES_Decrypt(bytesToBeDecrypted, passwordBytes);
string result = Encoding.UTF8.GetString(bytesDecrypted);
return result;
}
public byte[] AES_Decrypt(byte[] bytesToBeDecrypted, byte[] passwordBytes)
{
byte[] decryptedBytes = null;
using (MemoryStream ms = new MemoryStream())
{
using (Aes aes = Aes.Create())
{
aes.Key = passwordBytes;
aes.Mode = CipherMode.ECB;
aes.IV = new byte[16];
using (var cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(bytesToBeDecrypted, 0, bytesToBeDecrypted.Length);
cs.Close(); // here i am getting error
}
decryptedBytes = ms.ToArray();
}
}
return decryptedBytes;
}
You have two problems:
1) (Already pointed out by pedrofb): You use UTF8.GetBytes in encrypt, but SHA256(UTF8.GetBytes()) in decrypt.
You shouldn't do either of these methods, but instead should use a proper Password-Based Key-Derivation Function, such as PBKDF2. In .NET PBKDF2 is available via the Rfc2898DeriveBytes class.
byte[] salt = 8 or more bytes that you always pass in as the same.
// (salt could be fixed for your application,
// but if you have users it should be unique per user and stored along with the output value)
int iterations = 100000;
// Or bigger. If you were making a user management system you
// should write this number down, too, so you can increase it over time;
// it should be whatever number makes it take 100ms or more on the fastest relevant computer)
Rfc2898DeriveBytes pbkdf2 = new Rfc2898DeriveBytes(password, salt, iterations);
passwordBytes = pbkdf2.GetBytes(16); // 16 = AES128, 24 = AES192, 32 = AES256.
2) You use Base64-encoding in encrypt, but UTF8.GetBytes in decrypt.
Bonus problems:
3) You are using Electronic Codebook (ECB) chaining. Cipher Block Chaining (CBC) is recommended over ECB.
To use CBC properly, let a random initialization vector (IV) be generated in encrypt (which is done automatically when you create a new Aes object, or you can call GenerateIV() in encrypt if you re-use the object). Then you can just prepend the IV (which will always be 16 bytes for AES) to the ciphertext. In decrypt you can either a) chop off the first 16 bytes and assign it as the IV (then decrypt the rest of the data) or b) decrypt the whole blob and ignore the first 16 bytes of decrypted output.
You are hashing the password when you decrypt,
passwordBytes = SHA256.Create().ComputeHash(passwordBytes);
but not when encrypt. This means you are using different passwords

Secure token created in node different from .net

I'm trying to implement reCaptcha Secure Tokens in nodejs.
Looked at the examples made in Java and in .NET and created this version for node:
exports.getSecureToken = function() {
var algorithm = 'aes-128-ecb';
var tokenObj = { session_id: 'ab0069ec-3c2c-436c-868b-43c7a10db229'/*uuid.v4()*/, ts_ms: 1446560931992/*(new Date()).getTime()*/ };
var text = JSON.stringify(tokenObj);
var shaHash = new Buffer(crypto.createHash('sha1').update('6LeyNOTTVALIDH2RLNaivqrrpm2zh56Y3uHqOjFO'/*config.reCAPTCHASecret*/).digest('hex'), 'hex');
var key = shaHash.slice(0, 16);
var cipher = crypto.createCipher(algorithm, key, key);
var encryptedToken = cipher.update(text, 'utf8', 'base64') + cipher.final('base64');
var result = encryptedToken.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
return result;
};
Problem is that in .NET I get a token that works (using the right key not included in the post), but in node I get a different token for the same input, and it doesn't works:
.NET - LhPTUELia5vc0X6aDGDtqpsbmB7oqm6vUnzk5BL2auactYXRU5TEUzML8gZ_JubXG07rvJxk1Sb5_a-wqVUGEf_UuO1gGi-WO83yJHOxnjI
node - EGr7drd1JEylwzLGakZ6dpPRSf2nFdpzHOrJlLZlyHYmVRj5obAw7WjPt4W5l0vsywNEqCQ-2_d7qIZOMiOedianfBrQPOBaOmmq44IOB8Q
I got to see that key and input are the same (in .NET and node) right at the moment before encryption, so the problem must(?) be the cipher, any clues?
.NET code for reference:
public static void Main(string[] args)
{
//Your code goes here
Console.WriteLine(EncryptJsonToken(GetJsonToken()));
}
public static string GetJsonToken()
{
//Example: {"session_id": e6e9c56e-a7da-43b8-89fa-8e668cc0b86f,"ts_ms":1421774317718}
string jsonRequest = "{" + string.Format("\"session_id\": {0},\"ts_ms\":{1}", "ab0069ec-3c2c-436c-868b-43c7a10db229", 1446560931992) + "}";
return jsonRequest;
}
public static byte[] getKey()
{
string secretKey = "6LeyNOTTVALIDH2RLNaivqrrpm2zh56Y3uHqOjFO";
SHA1 sha = SHA1.Create();
byte[] dataToHash = Encoding.UTF8.GetBytes(secretKey);
byte[] shaHash = sha.ComputeHash(dataToHash);
byte[] first16OfHash = new byte[16];
Array.Copy(shaHash, first16OfHash, 16);
return first16OfHash;
}
public static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV)
{
// Check arguments.
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("IV");
byte[] encrypted;
// Create an AesManaged object
// with the specified key and IV.
using (AesManaged aesAlg = new AesManaged())
{
aesAlg.Key = Key;
aesAlg.IV = IV;
aesAlg.Padding = PaddingMode.PKCS7;
aesAlg.Mode = CipherMode.ECB;
// Create a decrytor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
// Return the encrypted bytes from the memory stream.
return encrypted;
}
public static string EncryptJsonToken(string jsonToken)
{
byte[] encrypted = EncryptStringToBytes_Aes(jsonToken, getKey(), getKey());
//Base64 encode the encrypted data
//Also applys the URL variant of base64 encoding, unfortunately the HttpServerUtility.UrlTokenEncode(encrypted) seems to truncate the last value from the string so we can't use it?
return Convert.ToBase64String(encrypted, Base64FormattingOptions.None).Replace("=", String.Empty).Replace('+', '-').Replace('/', '_');
}
To debug in .NET: DEMO
You have two problems:
You're using JSON.stringify() to produce a valid JSON string, but the GetJsonToken() method in the C# code doesn't produce a valid JSON string. There are " missing for the UUID and there is a space between the session_id key and its value for some reason. You have to reflect those differences in JavaScript:
var uuidToken = "ab0069ec-3c2c-436c-868b-43c7a10db229";
var time = 1446560931992;
var text = "{\"session_id\": "+uuidToken+",\"ts_ms\":"+time+"}";
There is no such function crypto.createCipher(algorithm, key, key). There is however crypto.createCipheriv(algorithm, key, iv). createCipher(algorithm, password) can be used if one has a password instead of a key which you don't have. Since there is no IV for ECB mode, you can pass in an empty (binary) string as the IV.
Full code:
var crypto = require("crypto");
var algorithm = 'aes-128-ecb';
var uuidToken = "ab0069ec-3c2c-436c-868b-43c7a10db229";
var time = 1446560931992;
var text = "{\"session_id\": "+uuidToken+",\"ts_ms\":"+time+"}";
console.log("Token: " + text);
var shaHash = crypto.createHash('sha1').update('6LeyNOTTVALIDH2RLNaivqrrpm2zh56Y3uHqOjFO').digest();
var key = shaHash.slice(0, 16);
var cipher = crypto.createCipheriv(algorithm, key, "");
var encryptedToken = cipher.update(text, 'utf8', 'base64') + cipher.final('base64');
var result = encryptedToken.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
console.log("result: " + result);
console.log("expected: LhPTUELia5vc0X6aDGDtqpsbmB7oqm6vUnzk5BL2auactYXRU5TEUzML8gZ_JubXG07rvJxk1Sb5_a-wqVUGEf_UuO1gGi-WO83yJHOxnjI");
Output:
Token: {"session_id": ab0069ec-3c2c-436c-868b-43c7a10db229,"ts_ms":1446560931992}
result: LhPTUELia5vc0X6aDGDtqpsbmB7oqm6vUnzk5BL2auactYXRU5TEUzML8gZ_JubXG07rvJxk1Sb5_a-wqVUGEf_UuO1gGi-WO83yJHOxnjI
expected: LhPTUELia5vc0X6aDGDtqpsbmB7oqm6vUnzk5BL2auactYXRU5TEUzML8gZ_JubXG07rvJxk1Sb5_a-wqVUGEf_UuO1gGi-WO83yJHOxnjI

AES-128-ECB - Inconsistent encryption result of node js and java

node js code:
function AES_encrypt(){
var bKey = new Buffer('24Qn9974h50D9DNi', 'utf-8');
var bInput = new Buffer(‘test’, 'utf-8');
console.log(bKey.length);
var cipher = crypto.createCipher('AES-128-ECB',bKey);
//cipher.setAutoPadding(auto_padding=false);
var crypted = cipher.update(bInput,null,'base64');
crypted+=cipher.final('base64');
console.log(crypted);
return crypted;
}
get Result:57b6b7oulw7eO5h7efZ9/w==
java code:
main java:
String data = AES.encryptToBase64("test","24Qn9974h50D9DNi");
AES java:
public static String encryptToBase64(String data, String key){
try {
byte[] valueByte = encrypt(data.getBytes("utf-8"), key.getBytes("utf-8");
return new String(Base64.encode(valueByte));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("encrypt fail!", e);
}
}
public static byte[] encrypt(byte[] data, byte[] key) {
if(key.length!=16){
throw new RuntimeException("Invalid AES key length (must be 16 bytes)");
}
try {
SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec seckey = new SecretKeySpec(enCodeFormat,"AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, seckey);// 初始化
byte[] result = cipher.doFinal(data);
return result; // 加密
} catch (Exception e){
throw new RuntimeException("encrypt fail!", e);
}
}
get Result:wA1JU6VxMaVl8Ck8pBrX8A==
Use crypto.createCipheriv to solve the issue,
http://nodejs.org/api/crypto.html#crypto_crypto_createcipheriv_algorithm_key_iv
You need to pad the string "test" to 16 bytes. I believe Java uses PKCS padding by default (but there are other padding schemes, too).
String data = AES.encryptToBase64("test","24Qn9974h50D9DNi");

Resources