0

我想实现 Java AES GCM 256 代码的 Javascript 等价物

Java代码如下:

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);
}

我如何实现相同的。我尝试了几种使用 SJCL 库的方法,但输出不匹配

  var string = "Hello World";
  var key = "";;
  var p = { mode: 'gcm', iv: sjcl.random.randomWords(4, 0) };
  var encrypted = sjcl.encrypt(key,string, p);
4

0 回答 0