I'm trying to convert this java code:
package ffsd;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class GatewayEncryptUtil {
public static String encrypt(String plainText, String key) throws Exception {
return new String(Base64.getEncoder().encode(doCrypt(plainText.getBytes(), 1, key)));
}
public static byte[] doCrypt(byte[] inputText, int operation, String key) throws Exception {
MessageDigest mDigest = MessageDigest.getInstance("SHA-512");
byte[] secretKey = key.getBytes();
byte[] digestSeed = mDigest.digest(secretKey);
byte[] hashKey = Arrays.copyOf(digestSeed, 16);
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
SecretKeySpec skspec = new SecretKeySpec(hashKey, "AES");
String cipherKey = new String(secretKey);
GCMParameterSpec gcmParams = new GCMParameterSpec(128, cipherKey.substring(0, 16).getBytes());
cipher.init(operation, skspec, gcmParams);
return cipher.doFinal(inputText);
}
public static void main(String[] args) {
try {
System.out.println(encrypt("Password", "1234567890123456"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
to C# .NET 5.0 using the new AesGcm class:
using System;
using System.Security.Cryptography;
using System.Text;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
string inputText = "Password";
string msgId = "1234567890123456";
byte[] hashKey;
byte[] secretKey = Encoding.ASCII.GetBytes(msgId);
using (var hasher = SHA512.Create())
{
byte[] digestSeed = hasher.ComputeHash(secretKey);
hashKey = new byte[16];
Array.Copy(digestSeed, hashKey, hashKey.Length);
}
using (var aesGcm = new AesGcm(hashKey))
{
byte[] nonce = new byte[AesGcm.NonceByteSizes.MaxSize];
byte[] plainText = Encoding.ASCII.GetBytes(inputText);
byte[] authTag = new byte[AesGcm.TagByteSizes.MaxSize];
byte[] cipherText = new byte[plainText.Length];
aesGcm.Encrypt(nonce, plainText, cipherText, authTag);
string cipherTextBase64 = Convert.ToBase64String(cipherText);
string authTagBase64 = Convert.ToBase64String(authTag);
Console.WriteLine(cipherTextBase64);
Console.WriteLine(authTagBase64);
}
}
}
}
But I don't know what the nonce is supposed to be. Not seeing that in the java code anywhere. Can anyone give me any pointers to this? The result of the java code is: "gc1zTHlIPQusN5e+Rjq+veDoIYdU1nCQ" mine is obviously incomplete and not coming close.