I use AES encryption in my react-native app as below
JavaScript
x
import CryptoJS from 'crypto-js' ;
encryptFun() {
var data = "123456";
var key = CryptoJS.enc.Latin1.parse('1234567812345678');
var iv = CryptoJS.enc.Latin1.parse('1234567812345678');
var encrypted = CryptoJS.AES.encrypt(
data,
key,
{iv:iv,mode:CryptoJS.mode.CBC,padding:CryptoJS.pad.ZeroPadding
});
console.log('encrypted: ' + encrypted) ;
var decrypted = CryptoJS.AES.decrypt(encrypted,key,{iv:iv,padding:CryptoJS.pad.ZeroPadding});
console.log('decrypted: '+decrypted.toString(CryptoJS.enc.Utf8));
}
Out come= encrypted: aK7+UX24ttBgfTnAndz9aQ==
following is the code I use in my backend using java for get the decrypt
JavaScript
public static String desEncrypt() throws Exception {
try
{
String data = "aK7+UX24ttBgfTnAndz9aQ==" ;
String key = "1234567812345678";
String iv = "1234567812345678";
byte[] encrypted1 = new BASE64Decoder().decodeBuffer(data);
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original);
return originalString;
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
output= decryted : = 123456[][][][][][][][][][]
Iam getting out put as 16 bit as above. what I want is out put should come as only 123456.
Advertisement
Answer
I Suggest you use java.util.Base64
for decoding. The following worked out correctly. I would also suggest using trim in return originalString
and see if it works out.
JavaScript
public class Decrypt {
public static void main(String[] args) {
try
{
String data = "aK7+UX24ttBgfTnAndz9aQ==" ;
String key = "1234567812345678";
String iv = "1234567812345678";
Decoder decoder = Base64.getDecoder();
byte[] encrypted1 = decoder.decode(data);
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original);
System.out.println(originalString.trim());
}
catch (Exception e) {
e.printStackTrace();
}
}
}