Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
I have a java version to do an encryption using AES GCM. When converting to C# I found the result is not the same. The C# code generates no error but resulted different value from Java version. I really have no idea about how to correct it.
public static void main(String args[]) {
String iv = "349ED607B1BDF85B";
String str = "secret";
String encrypted = encrypt(str,iv);
String decrypted = decrypt(encrypted,iv);
System.out.println("Encrypted = " + encrypted);
System.out.println("Decrypted = " + decrypted);
public static String encrypt(String plaintext, String iv) {
try {
Cipher instance = Cipher.getInstance("AES/GCM/NoPadding");
instance.init(1, key(), new GCMParameterSpec(128, iv.getBytes(StandardCharsets.UTF_8)));
byte[] doFinal = instance.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(doFinal);
} catch (Exception e) {
return "";
public static String decrypt(String cipherText, String iv) {
byte[] decodedBytes = Base64.getDecoder().decode(cipherText);
try {
Cipher instance = Cipher.getInstance("AES/GCM/NoPadding");
instance.init(2, key(), new GCMParameterSpec(128, iv.getBytes(StandardCharsets.UTF_8)));
byte[] doFinal = instance.doFinal(decodedBytes);
return new String(doFinal);
} catch (Exception e) {
return "";
private static SecretKeySpec key() {
String key = "8645eb9e5e59a7e021cf50c5b44346fa";
byte[] bytes = key.getBytes(StandardCharsets.UTF_8);
return new SecretKeySpec(bytes, 0, bytes.length, "AES");
C# version
public static string Encrypt(string plainText, string iv)
byte[] key = HexToByteArray("8645eb9e5e59a7e021cf50c5b44346fa");
byte[] ivBytes = AesGcm.HexToByteArray(iv); ;
var instance = CipherUtilities.GetCipher("AES/GCM/NoPadding");
instance.Init(true, new AeadParameters(new KeyParameter(key), 128, ivBytes));
var plainTextData = Encoding.ASCII.GetBytes(plainText);
var cipherText = instance.DoFinal(plainTextData);
return Convert.ToBase64String(cipherText);
–
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.