0

I want to implement the Javascript equivalent of Java AES GCM 256 code

Java code is as follows:

public class AES
{
private static final int GCM_IV_LENGTH = 12;
private static final int GCM_TAG_LENGTH = 16;
private static final String GIVEN_KEY = "";
public static String encrypt(String text) throws Exception
{
byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
Key secretKey = new SecretKeySpec(Base64.decodeBase64(GIVEN_KEY), "AES");
byte[] iv = new byte[GCM_IV_LENGTH];
new SecureRandom().nextBytes(iv);
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
SecretKeySpec keySpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, iv);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, gcmParameterSpec);
byte[] cipherText = cipher.doFinal(bytes);
byte[] finalArray = new byte[cipherText.length + GCM_IV_LENGTH];
System.arraycopy(iv, 0, finalArray, 0, GCM_IV_LENGTH);
System.arraycopy(cipherText, 0, finalArray, GCM_IV_LENGTH, cipherText.length);
return new String(Base64.encodeBase64URLSafe(finalArray), StandardCharsets.UTF_8);
}

How I can implement the same. I tried several methods using SJCL library but the output is not matching

  var string = "Hello World";
  var key = "";;
  var p = { mode: 'gcm', iv: sjcl.random.randomWords(4, 0) };
  var encrypted = sjcl.encrypt(key,string, p);
  • 1
    See [this](https://gist.github.com/rjz/15baffeab434b8125ca4d783f4116d81). Is what are you looking for? – Carlo Corradini Jul 04 '20 at 17:33
  • The result may not match when using a _random_ IV (whereby it's perfectly correct to use a random IV). The decisive factor is whether the encryption of the JavaScript code can be decrypted with the (not posted) decryption method of the Java code. If so, both encryptions are equivalent. – Topaco Jul 04 '20 at 19:40
  • In the Java code, the 16 bytes authentication tag is _implicitly_ appended to the ciphertext. This seems to be also the case with the sjcl library, [here](https://bitwiseshiftleft.github.io/sjcl/doc/gcm.js.html). In the Java code, the 12 bytes nonce is placed _explicitly_ in front of the ciphertext (i.e. the result consists of IV, ciphertext, tag, in that order). The JavaScript code must generate the _same_ sequence. The codes also differ in other details, such as the encoding of the ciphertext. – Topaco Jul 04 '20 at 19:40

0 Answers0