title: Encrypt AES-GCM in JavaScript, decrypt in Java
body: <p>We are using the SJCL (Stanford Javascript Crypto Library) to encrypt in JavaScript and we are supposed to implement decryption in Java.</p>
  
  <p>The encryption code looks like this:</p>
  
  <pre><code>&lt;script src='https://cdnjs.cloudflare.com/ajax/libs/sjcl/1.0.7/sjcl.js'&gt;&lt;/script&gt;
  
  &lt;script&gt;
  var keyString = '2d73c1dd2f6a3c981afc7c0d49d7b58f';
  var key = sjcl.codec.base64.toBits(keyString);
  var cipher = new sjcl.cipher.aes(key)
  var data = sjcl.codec.utf8String.toBits('Hello Crypto!'); 
  var salt = sjcl.codec.base64url.toBits('kLME6vN-WdU_W9XVN9a1Z3E_p8HQ5C7X1La-3ZjEml1ytVRMfvtEXzeapbce2LjFI1dHEGtWv9bZ_U6K2CG1-K4lQPunFXWxXmsTQIXlGfwmpveg2AFeLFiqGmALnfbP');
  var encrypted = sjcl.encrypt(keyString,'Hello Crypto!',{mode:'gcm',salt:salt});
  
  console.log(encrypted)
  &lt;/script&gt;
  </code></pre>
  
  <p>The resulting encryption looks like the following:</p>
  
  <pre><code>{
     "iv":"+xmg3yZF/LSWNFpXf03wUw==",
     "v":1,
     "iter":10000,
     "ks":128,
     "ts":64,
     "mode":"gcm",
     "adata":"",
     "cipher":"aes",
     "salt":"kLME6vN+WdU/W9XVN9a1Z3E/p8HQ5C7X1La+3ZjEml1ytVRMfvtEXzeapbce2LjFI1dHEGtWv9bZ/U6K2CG1+K4lQPunFXWxXmsTQIXlGfwmpveg2AFeLFiqGmALnfbP",
     "ct":"Nq+9tXfc0zs0/m3OfDp0MmTXc9qD"
  }
  </code></pre>
  
  <p>We were supplied with sample Java code to decrypt the code but this code assumes that IV and salt is the same thing so it won't work with the JSON that we are getting from the JS lib (having IV and salt as two separate values):</p>
  
  <pre><code> final byte[] symKeyData = DatatypeConverter.parseHexBinary(keyHex);
   final byte[] ivData = ivSalt.getBytes(Charset.forName("UTF-8"));
   final byte[] encryptedMessage = DatatypeConverter.parseBase64Binary(encryptedMessageString);
   final Cipher cipher = javax.crypto.Cipher.getInstance("AES/GCM/NoPadding", "BC");
   final SecretKeySpec symKey = new SecretKeySpec(symKeyData, "AES");
   final IvParameterSpec iv = new IvParameterSpec(ivData);
   cipher.init(Cipher.DECRYPT_MODE, symKey, iv);
   final byte[] encodedMessage = cipher.doFinal(encryptedMessage);
   final String message = new String(encodedMessage, Charset.forName("UTF-8"));
  </code></pre>
  
  <p>Can anybody explain how the resulting JSON from the JavaScript library can be decrypted correctly in Java?</p>