Encoding in JavaScript - javascript

I'm very new in programming with Javascript and stuck in encoding my data.
I have done this as per need in my Android App, but could not able to do the same in JavaScript for my web portal.
The code which I'm using in Android App:
public void encryptdata(byte[] data) {
Encrypter encrypter = new Encrypter();
HashGenerator hashGenerator = new HashGenerator();
try {
byte[] e = encrypter.generateSessionKey();
byte[] encryptedData = encrypter.encryptUsingSessionKey(e, data);
byte[] hmac = hashGenerator.generateSha256Hash(data);
byte[] encryptedHmacBytes = encrypter.encryptUsingSessionKey(e, hmac);
this.encodedSessionKey = encodeBase64(e);
this.encodedHmac = encodeBase64(encryptedHmacBytes);
this.encodedData = encodeBase64(encryptedData);
} catch (Exception var6) {
var6.printStackTrace();
throw new RuntimeException(var6);
}
}
Encrypter.java
class Encrypter {
private static final String JCE_PROVIDER = "BC";
private static final int SYMMETRIC_KEY_SIZE = 256;
Encrypter() {
}
public byte[] generateSessionKey() throws NoSuchAlgorithmException, NoSuchProviderException {
KeyGenerator kgen = KeyGenerator.getInstance("AES", "BC");
kgen.init(256);
SecretKey key = kgen.generateKey();
byte[] symmKey = key.getEncoded();
return symmKey;
}
public byte[] encryptUsingSessionKey(byte[] skey, byte[] data) throws InvalidCipherTextException {
PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new AESEngine(), new PKCS7Padding());
cipher.init(true, new KeyParameter(skey));
int outputSize = cipher.getOutputSize(data.length);
byte[] tempOP = new byte[outputSize];
int processLen = cipher.processBytes(data, 0, data.length, tempOP, 0);
int outputLen = cipher.doFinal(tempOP, processLen);
byte[] result = new byte[processLen + outputLen];
System.arraycopy(tempOP, 0, result, 0, result.length);
return result;
}
static {
Security.addProvider(new BouncyCastleProvider());
}
}
HashGenerator.java
class HashGenerator {
public HashGenerator() {
}
public byte[] generateSha256Hash(byte[] message) {
String var2 = "SHA-256";
String var3 = "BC";
byte[] var4 = null;
try {
MessageDigest var7 = MessageDigest.getInstance(var2, var3);
var7.reset();
var4 = var7.digest(message);
} catch (Exception var6) {
var6.printStackTrace();
}
return var4;
}
}
These piece of code encoding the data and giving me HMAC as per my need, but I am not able to do same with JavaScript.
Can anyone give any reference or code on for JavaScript client.
Any help will be appreciated.

Thanks for down-voting the question, may be a not great question, but here I done it myself
this.doEncryption = function (data) {
var key = btoa(this.generateRandomString());
var Encryptionkey = CryptoJS.enc.Base64.parse(key);
var encryptedPid = CryptoJS.AES.encrypt(data,Encryptionkey,{ mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7});
var sha256 = CryptoJS.SHA256(data);
var encryptedHmac = CryptoJS.AES.encrypt(sha256,Encryptionkey,{ mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7});
return {
encryptionKey : key,
encryptedPid : encryptedPid.toString(),
encryptedHmac : encryptedHmac.toString()
};

Related

Crypto JS and Java Security Library for replicate both Encryption and Decryption

Here is my AES Library in Java:
public class AESUtil {
private SecretKeySpec secretKey;
public static void main(String[] args) {
String str = args[1];
String salt = args[2];
AESUtil aesUtil = new AESUtil();
if (args[0].equals("D")) {
//Going to Decrypt
System.out.println(aesUtil.decrypt(str, salt));
} else {
//Going to Encrypt
System.out.println(aesUtil.encrypt(str, salt));
}
}
public String encrypt(final String strToEncrypt, final String secret) {
try {
setKey(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return Base64.getEncoder()
.encodeToString(cipher.doFinal(strToEncrypt.getBytes(StandardCharsets.UTF_8)));
} catch (Exception e) {
System.out.println("Error while encrypting: " + e.toString());
}
return null;
}
public String decrypt(final String strToDecrypt, final String secret) {
try {
setKey(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return new String(cipher.doFinal(Base64.getDecoder()
.decode(strToDecrypt)));
} catch (Exception e) {
System.out.println("Error while decrypting: " + e.toString());
}
return null;
}
private void setKey(final String myKey) {
MessageDigest sha = null;
try {
byte[] key = myKey.getBytes(StandardCharsets.UTF_8);
sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16);
secretKey = new SecretKeySpec(key, "AES");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
}
Here is my Decryption Logic in Javascript using CryptoJS lib:
function decrypt() {
var hashedKey = CryptoJS.SHA1(CryptoJS.enc.Utf8.parse(document.getElementById("pass").value));
console.log(hashedKey)
var encryptedCipherText = document.getElementById("text").value;
console.log(encryptedCipherText)
var decryptedData = CryptoJS.AES.decrypt(encryptedCipherText, hashedKey,
{
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
})
console.log(decryptedData)
var decryptedText = decryptedData.toString(CryptoJS.enc.Utf8);
console.log(decryptedText)
document.getElementById("decrypted").innerHTML = decryptedText;
document.getElementById("result").innerHTML = '';
}
In Java:
For:
Plain Text: This Value is to Encrypt
Secret: shh!
Encrypted Value: i8DHmeHuoQWv3rwZ+cybgSdSkyUX7MAcU54NUf2iyxU=
However when putting the same value in Javascript:
I have a high suspect on SHA1 logic i have in Java, that might be causing the issue. But not sure on how to validate that.

Encryption - Decryption between Java and React Js

I am unable to create a successful encryption in React Js that can be decrypted in Java.
Below is the code --
import React, { Component } from "react";
import { Row, Col, Typography, Spin } from "antd";
import { withRouter } from "react-router-dom";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import * as Crypto from 'crypto-js';
import * as utf8 from 'utf8';
import { Calendar } from "antd";
class Test extends Component {
state = {};
componentDidMount = () => {
debugger;
var keySize = 0;
var ivSize = 16;
var saltSize = 16;
var iterations = 4096;
var pass = 'mysuperstrongpassword';
var passMac = 'mysuperstrongpasswordMac';
let message = 'Gurpreet';
const CryptoJS = require("crypto-js")
var Crypto = new AES()
function AES() {}
AES.prototype.generateKey = function(salt, passPhrase) {
var key = CryptoJS.PBKDF2(passPhrase, CryptoJS.enc.Hex.parse(salt), { keySize: 256/16, iterations: 4096 });
return key;
}
AES.prototype.encrypt = function(password, message) {
var salt = CryptoJS.lib.WordArray.random(128/8).toString(CryptoJS.enc.Hex)
var iv = CryptoJS.lib.WordArray.random(128/8).toString(CryptoJS.enc.Hex)
var encrypted = CryptoJS.AES.encrypt(message, this.generateKey(salt, password), { iv: CryptoJS.enc.Hex.parse(iv) })
var base64 = encrypted.ciphertext.toString(CryptoJS.enc.Base64)
return salt + base64.substring(0, base64.length-2) + iv
}
AES.prototype.decrypt = function(password, message) {
var salt = message.substring(0, 32)
var iv = message.substring(message.length-32, message.length)
var cipherParams = CryptoJS.lib.CipherParams.create({
ciphertext: CryptoJS.enc.Base64.parse(message.substring(32, message.length-32) + "==")
});
var decrypted = CryptoJS.AES.decrypt(cipherParams, this.generateKey(salt, password), { iv: CryptoJS.enc.Hex.parse(iv) })
return decrypted.toString(CryptoJS.enc.Utf8)
}
//var rest = btoa(hmac + result);
var salt = CryptoJS.lib.WordArray.random(128/8).toString(CryptoJS.enc.Hex);
var saltMac = CryptoJS.lib.WordArray.random(20).toString(CryptoJS.enc.Hex)
var iv = CryptoJS.lib.WordArray.random(128/8).toString(CryptoJS.enc.Hex)
var macKey = AES.prototype.generateKey(saltMac, passMac)
var rest = AES.prototype.encrypt(pass, message)
var hmac = CryptoJS.HmacSHA1(passMac, macKey);
let result = hmac + salt + saltMac + rest;
let result2 = CryptoJS.enc.Utf8.parse(result).toString();
var rest2 = btoa(result2);
console.log(rest2);
console.log(result2);
};
render() {
return (
<div className="test">
href={this.rest}
</div>
);
}
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({}, dispatch);
}
export default withRouter(
connect(null, mapDispatchToProps, null, { forwardRef: true })(Test)
);
Java
public class EncryptDecryptUtil {
// private static final String CONTENT = "thisneedstobestoredverysecurely";
private static final String PASSPHRASE = "mysuperstrongpassword";
private static final String PASSPHRASEMAC = "mysuperstrongpasswordMac";
private static final int IV_LENGTH = 16;
private static final int AES_KEY_LENGTH = 16;
private static final int MAC_KEY_LENGTH = 16;
private static final int MAC_LENGTH = 20;
private static final int SALT_LENGTH = 16;
private static final int SALT_MAC_LENGTH = 16;
private static final int ITERATION_COUNT = 4096;
private static final String AES = "AES";
private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
private static final String SECRET_KEY_ALGORITHM = "PBKDF2WithHmacSHA1";
private static final String MAC_ALGORITHM = "HmacSHA1";
Cipher cipher = null;
byte[] iv = new byte[IV_LENGTH];
byte[] secretBytes = null;
byte[] secretBytesMac = null;
public String encrypt(String plainText) throws Exception {
cipher = Cipher.getInstance(CIPHER_ALGORITHM);
SecretKeyFactory factory = SecretKeyFactory.getInstance(SECRET_KEY_ALGORITHM);
SecureRandom sr = new SecureRandom();
byte[] salt = new byte[SALT_LENGTH];
sr.nextBytes(salt);
SecretKey secretKey = factory
.generateSecret(new PBEKeySpec(PASSPHRASE.toCharArray(), salt, ITERATION_COUNT, 256));
secretBytes = secretKey.getEncoded();
byte[] saltMac = new byte[SALT_MAC_LENGTH];
sr.nextBytes(saltMac);
SecretKey secretKeyMac = factory
.generateSecret(new PBEKeySpec(PASSPHRASEMAC.toCharArray(), saltMac, ITERATION_COUNT, 256));
secretBytesMac = secretKeyMac.getEncoded();
sr = new SecureRandom();
sr.nextBytes(iv);
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(secretBytes, 0, AES_KEY_LENGTH, AES),
new IvParameterSpec(iv));
byte[] encrypted = cipher.doFinal(plainText.getBytes("UTF-8"));
byte[] result = concatArrays(iv, concatArrays(saltMac, (concatArrays(salt, encrypted))));
byte[] macResult = getMAC(secretBytesMac, result);
result = concatArrays(macResult, result);
return Base64.getEncoder().encodeToString(result);
}
public String decrypt(String cipherText) throws Exception {
byte[] result = Base64.getDecoder().decode(cipherText);
byte[] macResult = new byte[MAC_LENGTH];
byte[] salt = new byte[SALT_LENGTH];
byte[] saltMac = new byte[SALT_MAC_LENGTH];
cipher = Cipher.getInstance(CIPHER_ALGORITHM);
System.arraycopy(result, 0, macResult, 0, MAC_LENGTH);
System.arraycopy(result, MAC_LENGTH, iv, 0, IV_LENGTH);
System.arraycopy(result, MAC_LENGTH + IV_LENGTH, saltMac, 0, SALT_MAC_LENGTH);
System.arraycopy(result, MAC_LENGTH + IV_LENGTH + SALT_MAC_LENGTH, salt, 0, SALT_LENGTH);
byte[] encrypted = new byte[result.length - (MAC_LENGTH + IV_LENGTH + SALT_MAC_LENGTH + SALT_LENGTH)];
System.arraycopy(result, MAC_LENGTH + IV_LENGTH + SALT_MAC_LENGTH + SALT_LENGTH, encrypted, 0,
encrypted.length);
SecretKeyFactory factory = SecretKeyFactory.getInstance(SECRET_KEY_ALGORITHM);
SecretKey secretKeyMac = factory
.generateSecret(new PBEKeySpec(PASSPHRASEMAC.toCharArray(), saltMac, ITERATION_COUNT, 256));
secretBytesMac = secretKeyMac.getEncoded();
if (!MessageDigest.isEqual(
getMAC(secretBytesMac, concatArrays(iv, concatArrays(saltMac, (concatArrays(salt, encrypted))))),
macResult)) {
System.out.println("Invalid MAC");
}
SecretKey secretKey = factory
.generateSecret(new PBEKeySpec(PASSPHRASE.toCharArray(), salt, ITERATION_COUNT, 256));
secretBytes = secretKey.getEncoded();
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(secretBytes, 0, AES_KEY_LENGTH, AES),
new IvParameterSpec(iv));
byte[] decrypted = cipher.doFinal(encrypted);
return new String(decrypted, "UTF-8");
}
private static byte[] getDigest(byte[] mac) throws Exception {
MessageDigest digest = MessageDigest.getInstance("SHA1");
return digest.digest(mac);
}
private static byte[] getMAC(byte[] secretBytes, byte[] data) throws Exception {
Mac mac = Mac.getInstance(MAC_ALGORITHM);
mac.init(new SecretKeySpec(secretBytes, 0, MAC_KEY_LENGTH, MAC_ALGORITHM));
return mac.doFinal(data);
}
private static byte[] concatArrays(byte[] first, byte[] second) {
byte[] ret = new byte[first.length + second.length];
System.arraycopy(first, 0, ret, 0, first.length);
System.arraycopy(second, 0, ret, first.length, second.length);
return ret;
}
}
I cant change anything at Java Backend because for the iOS team they are able to encrypt-decrypt using this util and are sending us the correct strings.
But the issue is at Web end #React Js end - code above where we are unable to match the encryption technique same as Java.

Encrypted in C#. Need decryption in NodeJS

I barely have any knowledge on c#. I have a scenario where I have encryption and decryption in c# as follows. But, I want to implement same decryption in NodeJS. Can anyone help me in figuring this out.
Here's the salt and secret keys
private static byte[] _salt = Encoding.ASCII.GetBytes("SampleSaltHere");
private string secret = "SecretHere";
Encryption Part
public string Encrypt(string plainText)
{
string outStr = null;
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(secret, _salt);
RijndaelManaged aesAlg = new RijndaelManaged();
aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msEncrypt = new MemoryStream())
{
msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int));
msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(plainText);
}
}
outStr = Convert.ToBase64String(msEncrypt.ToArray());
}
return outStr;
}
Decryption Part which I want to implement in NodeJS.
public string Decrypt(string cipherText)
{
string plaintext = null;
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(secret, _salt);
byte[] bytes = Convert.FromBase64String(cipherText);
using (MemoryStream msDecrypt = new MemoryStream(bytes))
{
RijndaelManaged aesAlg = new RijndaelManaged();
aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
aesAlg.IV = ReadByteArray(msDecrypt);
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
plaintext = srDecrypt.ReadToEnd();
}
}
return plaintext;
}
private static byte[] ReadByteArray(Stream s)
{
byte[] rawLength = new byte[sizeof(int)];
byte[] buffer = new byte[BitConverter.ToInt32(rawLength, 0)];
return buffer;
}
Any help is highly appreciated. Thank you.

react-native AES Encryption matching Java Decryption algorithm

The Full code of my Java Encryption/Decryption algorithm:
public class AESEncryptUtil {
private static AESEncryptUtil instance = new AESEncryptUtil();
private String password = "123456";
private Key key;
private Cipher cipher;
public AESEncryptUtil(){
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, new SecureRandom(password.getBytes()));
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
key = new SecretKeySpec(enCodeFormat, "AES");
cipher = Cipher.getInstance("AES");
} catch (Exception e) {
e.printStackTrace();
}
}
public static byte[] encrypt(String content) throws Exception {
byte[] byteContent = content.getBytes("utf-8");
instance.cipher.init(Cipher.ENCRYPT_MODE, instance.key);
byte[] result = instance.cipher.doFinal(byteContent);
return result;
}
public static byte[] decrypt(byte[] content) throws Exception {
instance.cipher.init(Cipher.DECRYPT_MODE, instance.key);
byte[] result = instance.cipher.doFinal(content);
return result;
}
public static String parseByte2HexStr(byte buf[]) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
public static byte[] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < 1)
return null;
byte[] result = new byte[hexStr.length() / 2];
for (int i = 0; i < hexStr.length() / 2; i++) {
int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2),
16);
result[i] = (byte) (high * 16 + low);
}
return result;
}
public static String getNonce() {
String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 16; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
public static void main(String[] args) throws Exception {
String content = "test";
System.out.println("content: " + content);
byte[] encryptResult = encrypt(content);
String encryptResultStr = parseByte2HexStr(encryptResult);
System.out.println("encryptResultStr: " + encryptResultStr);
byte[] decryptFrom = parseHexStr2Byte(encryptResultStr);
byte[] decryptResult = decrypt(decryptFrom);
System.out.println("decryptResult: " + new String(decryptResult));
}
}
I've tried many times and many ways to match the Java algorithm, but the result are always different. Which module should I use to do this ? Can anyone help me to deal it ? Thanks a lot !
I found the right way to match two algorithm:
Java part:
public static String encrypt() throws Exception {
try {
String data = "123456";
String key = "1234567812345678";
String iv = "1234567812345678";
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
int blockSize = cipher.getBlockSize();
byte[] dataBytes = data.getBytes();
int plaintextLength = dataBytes.length;
if (plaintextLength % blockSize != 0) {
plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
}
byte[] plaintext = new byte[plaintextLength];
System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
byte[] encrypted = cipher.doFinal(plaintext);
return new sun.misc.BASE64Encoder().encode(encrypted);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String desEncrypt() throws Exception {
String encrypted = encrypt() ;
try
{
String data = encrypted ;
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;
}
}
React native part:
pre coding: npm install crypto-js
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));
}
the result :
encrypted: aK7+UX24ttBgfTnAndz9aQ==
decrypted: 123456
I hope my code would help someone:)

crypto-js - read and decrypt file

I have some Java functions for doing AES encryption, one for a string, and one for a file
private static final String AES_CIPHER_METHOD = "AES";
public static SecretKeySpec createAesKeySpec(byte[] aesKey) {
return new SecretKeySpec(aesKey, AES_CIPHER_METHOD);
}
public static String aesEncrypt(String data, SecretKeySpec aesKeySpec) throws EncryptionException {
try {
Cipher aesCipher = Cipher.getInstance(AES_CIPHER_METHOD);
aesCipher.init(Cipher.ENCRYPT_MODE, aesKeySpec);
byte[] encVal = aesCipher.doFinal(data.getBytes("UTF8"));
return new BASE64Encoder().encode(encVal);
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IOException | BadPaddingException| IllegalBlockSizeException e) {
throw new EncryptionException(e.getMessage(), e);
}
}
public static void aesEncryptFile(File in, File out, SecretKeySpec aesKeySpec) throws EncryptionException {
try {
Cipher aesCipher = Cipher.getInstance(AES_CIPHER_METHOD);
aesCipher.init(Cipher.ENCRYPT_MODE, aesKeySpec);
try (InputStream inputStream = new FileInputStream(in)) {
try (OutputStream outputStream = new CipherOutputStream(new FileOutputStream(out), aesCipher)){
IOUtils.copy(inputStream, outputStream);
}
}
} catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | IOException e){
throw new EncryptionException(e.getMessage(), e);
}
}
I also have some tests to output some test data
private static final String KEY_STRING = "DpiA4l0gvb7biWZtiN6Vjg==";
private SecretKeySpec createKeySpec() {
byte[] keyBytes = new Base64().decode(KEY_STRING.getBytes());
return EncryptionUtils.createAesKeySpec(keyBytes);
}
public void testAesEncryptString() throws EncryptionException {
String encryptedData = EncryptionUtils.aesEncrypt("A normal string", createKeySpec());
System.out.println(encryptedData); //outputs 3XLwlSHWLm98teIoIS6QTA==
}
public void testAesEncryptStringFile() throws EncryptionException, IOException {
File newFile = new File(FilenameUtils.concat(System.getProperty("java.io.tmpdir"), "myFile.txt"));
FileUtils.writeStringToFile(newFile, "A string in a file");
File encryptedFile = new File(FilenameUtils.concat(System.getProperty("java.io.tmpdir"), "myFile_encrypted.txt"));
EncryptionUtils.aesEncryptFile(newFile, encryptedFile, createKeySpec());
}
I now need to implement decryption in javascript.
I have managed to successfully decrypt the plain string using crypto-js, however, I just cant get the file part working, and I cant quite see what is wrong
var base64Key = "DpiA4l0gvb7biWZtiN6Vjg==";
var key = CryptoJS.enc.Base64.parse(base64Key);
var aesOptions = {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
};
var decryptedData = CryptoJS.AES.decrypt( "3XLwlSHWLm98teIoIS6QTA==", key, aesOptions);
var decryptedText = decryptedData.toString( CryptoJS.enc.Utf8 );
console.log( "decryptedText = " + decryptedText ); //CORRECT outputs "A normal string"
var encryptedFilename = "https://dl.dropboxusercontent.com/u/30823828/myFile_encrypted.txt";
$.get(encryptedFilename, function(data){
console.log("encrypted file content", data);
var encryptedData = CryptoJS.enc.Base64.parse(data);
var decryptedData = CryptoJS.AES.decrypt( encryptedData, key, aesOptions);
var decryptedText = decryptedData.toString( CryptoJS.enc.Utf8 );
console.log( "decrypted file content = " + decryptedText ); //INCORRECT outputs "" SHOULD output "A string in a file"
});
link to jsfiddle - http://jsfiddle.net/pKNzV/46/
after a lot of trial and error, I was able to get this working.
the function base64ArrayBuffer comes from the following - https://gist.github.com/jonleighton/958841
var base64Key = "DpiA4l0gvb7biWZtiN6Vjg==";
var key = CryptoJS.enc.Base64.parse(base64Key);
var aesOptions = {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
};
var encryptedFilename = "https://dl.dropboxusercontent.com/u/30823828/myFile_encrypted.txt";
var oReq = new XMLHttpRequest();
oReq.open("GET", encryptedFilename, true);
oReq.responseType = "arraybuffer";
oReq.onload = function (oEvent) {
var data = oReq.response;
if (data) {
encodedData = base64ArrayBuffer(data);
var decryptedData = CryptoJS.AES.decrypt( encodedData, key, aesOptions);
var decryptedText = decryptedData.toString( CryptoJS.enc.Utf8 );
console.log( "decryptedText = " + decryptedText );
console.log("file decrypt successful: ", "A string in a file" === decryptedText);
}
};
oReq.send(null);

Categories

Resources