SecretKeySpec in javascript [duplicate]

Solution 1:

It is not possible to convert Java code to Javascript directly. If you are looking for a simple converter that would automatcally convert your Java logic or functions into Javascript ...then it doesn't exist.

You may have to find the appropriate libraries and functions in Javascript. And then write new fresh code which would implement the same logic in Javascript.

Having said that, CryptoJS is a good matured javascript library that supports the various crypto standards. Please refer it and write your code in Javascript.

By looking at your Java code , I believe that you are trying to encrypt a piece of text using a secret key. Please have a look at the code below written in Javascript :

var salt = CryptoJS.lib.WordArray.random(128/8);
var iv = CryptoJS.lib.WordArray.random(128/8);


function  encrypt(){
  console.log('salt  '+ salt );
  console.log('iv  '+ iv );
  var key128Bits = CryptoJS.PBKDF2("Secret Passphrase", salt, { keySize: 128/32 }); 
  console.log( 'key128Bits '+ key128Bits);
  var key128Bits100Iterations = CryptoJS.PBKDF2("Secret Passphrase", salt, { keySize: 128/32, iterations: 100 });
  console.log( 'key128Bits100Iterations '+ key128Bits100Iterations);
  var encrypted = CryptoJS.AES.encrypt("Message", key128Bits100Iterations, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7  });
  console.log('encrypted   '+ encrypted  );
}



function  decrypt(encrypted){
 // var salt = CryptoJS.enc.Hex.parse("4acfedc7dc72a9003a0dd721d7642bde");
 // var iv = CryptoJS.enc.Hex.parse("69135769514102d0eded589ff874cacd");
 // var encrypted = "PU7jfTmkyvD71ZtISKFcUQ==";
  console.log('salt  '+ salt );
  console.log('iv  '+ iv );
  var key = CryptoJS.PBKDF2("Secret Passphrase", salt, { keySize: 128/32, iterations: 100 });
  console.log( 'key '+ key);
  var decrypt = CryptoJS.AES.decrypt(encrypted, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
  var ddd = decrypt.toString(CryptoJS.enc.Utf8); 
  console.log('ddd '+ddd);
}