在Android/Java和Web/JavaScript之间使用AES-GCM加密算法,可以通过以下步骤来实现兼容性:
SecureRandom secureRandom = new SecureRandom();
byte[] key = new byte[16];
secureRandom.nextBytes(key);
byte[] iv = new byte[12];
secureRandom.nextBytes(iv);
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
public class AesGcmEncryption {
public static byte[] encrypt(String plaintext, byte[] key, byte[] iv) throws Exception {
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
SecretKey secretKey = new SecretKeySpec(key, "AES");
GCMParameterSpec parameterSpec = new GCMParameterSpec(128, iv);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, parameterSpec);
return cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
}
public static String decrypt(byte[] ciphertext, byte[] key, byte[] iv) throws Exception {
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
SecretKey secretKey = new SecretKeySpec(key, "AES");
GCMParameterSpec parameterSpec = new GCMParameterSpec(128, iv);
cipher.init(Cipher.DECRYPT_MODE, secretKey, parameterSpec);
byte[] plaintextBytes = cipher.doFinal(ciphertext);
return new String(plaintextBytes, StandardCharsets.UTF_8);
}
}
async function encrypt(plaintext, key, iv) {
const encodedKey = await crypto.subtle.importKey(
'raw', key, 'AES-GCM', false, ['encrypt']
);
const encryptedData = await crypto.subtle.encrypt(
{name: 'AES-GCM', iv}, encodedKey, new TextEncoder().encode(plaintext)
);
return new Uint8Array(encryptedData);
}
async function decrypt(ciphertext, key, iv) {
const encodedKey = await crypto.subtle.importKey(
'raw', key, 'AES-GCM', false, ['decrypt']
);
const decryptedData = await crypto.subtle.decrypt(
{name: 'AES-GCM', iv}, encodedKey, ciphertext
);
return new TextDecoder().decode(decryptedData);
}
这样,你就可以在Android/Java和Web/JavaScript之间使用相同的AES-GCM加密算法进行数据加密和解密了。请注意,这只是一个简单的示例,实际使用时还需要考虑更多的安全性和错误处理。