Код: Выделить всё
public class CustomAESGCMCryptor {
private BytesEncryptor encryptor;
public CustomAESGCMCryptor(String secretKey) {
encryptor = new BouncyCastleAesGcmBytesEncryptor("", secretKey);
}
public String encrypt(String text) {
return new String(Base64.encode(encryptor.encrypt(text.getBytes())), StandardCharsets.UTF_8);
}
}
Симметричный ключ генерируется с использованием приведенного ниже кода -
private String generateSymmetricKey() throws NoSuchAlgorithmException {
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256);
Key key = keyGen.generateKey();
return new String(encodeHex(key.getEncoded()));
}
< /code>
Я должен расшифровать текст шифра в C#, для которого я использую приведенный ниже код -< /p>
namespace Symmetric_Decryption_AES_GCM_C_ {
class Program
{
static void Main(string[] args)
{
String encryptedToken = "cipher";
String secretKey = "key";
Console.WriteLine(DecryptPayload(encryptedToken, secretKey));
}
private static string DecryptPayload(string base64EncryptedToken, string stringKey)
{
Console.WriteLine("----C# Decryption Details----");
byte[] encryptedToken = Convert.FromBase64String(base64EncryptedToken); // Converting the base64 string encrypted text to byte[]
byte[] key = Enumerable.Range(0, stringKey.Length / 2)
.Select(i => Convert.ToByte(stringKey.Substring(i * 2, 2), 16))
.ToArray(); // Converting hex encoded key to byte[]
int ivLength = 16;
int ciphertextTagLength = encryptedToken.Length - ivLength;
byte[] iv = new byte[ivLength];
byte[] ciphertextTag = new byte[ciphertextTagLength];
Buffer.BlockCopy(encryptedToken, 0, iv, 0, ivLength);
Buffer.BlockCopy(encryptedToken, ivLength, ciphertextTag, 0, ciphertextTagLength);
return DecryptWithGCM(ciphertextTag, key, iv);
}
private static string DecryptWithGCM(byte[] ciphertextTag, byte[] key, byte[] nonce)
{
var cipher = new GcmBlockCipher(new AesEngine());
cipher.Init(false, new AeadParameters(new KeyParameter(key), 128, nonce, null));
int outputSizeDecryptedData = cipher.GetOutputSize(ciphertextTag.Length);
byte[] decryptedBytes = new byte[outputSizeDecryptedData];
int processedBytes = cipher.ProcessBytes(ciphertextTag, 0, ciphertextTag.Length, decryptedBytes, 0);
cipher.DoFinal(decryptedBytes, processedBytes);
return Encoding.UTF8.GetString(decryptedBytes);
}
}
}
< /code>
Этот код расшифровки работает нормально, если я зашифрую текст в C#, следовательно, код работает.
Но когда я даю зашифрованный текст, сгенерированный из кода Java, я получаю - 'Mac Проверка в GCM'.>
Подробнее здесь: https://stackoverflow.com/questions/797 ... cm-which-i