private static string Decryptv2(Func <string, X509Certificate2> certResolver, MemoryStream inputStream, BinaryReader reader) { int version = 2; string thumbprint = ToHexString(reader.ReadBytes(20), 0, 20); X509Certificate2 cert = certResolver(thumbprint); int encryptedKeyLength = reader.ReadInt32(); int nonceLength = reader.ReadInt32(); int tagLength = reader.ReadInt32(); byte[] encryptedKey = reader.ReadBytes(encryptedKeyLength); byte[] nonce = reader.ReadBytes(nonceLength); byte[] tag = reader.ReadBytes(tagLength); RSA privateKey = cert.GetRSAPrivateKey(); byte[] decryptedKey = privateKey.Decrypt(encryptedKey, RSAEncryptionPadding.OaepSHA512); int remainingBytes = (int)(inputStream.Length - inputStream.Position); byte[] encryptedData = reader.ReadBytes(remainingBytes); byte[] decryptedData = new byte[remainingBytes]; byte[] additionalData = new byte[] { Convert.ToByte(version) }; using (AesGcm aes = new AesGcm(decryptedKey)) { aes.Decrypt(nonce, encryptedData, tag, decryptedData, additionalData); } return(Encoding.UTF8.GetString(decryptedData)); }
/* * 解密算法 */ static void decrypt(byte[] ciphertext, byte[] tag, byte[] key, byte[] iv, byte[] plaintext) { var aesGcm = new AesGcm(key); aesGcm.Decrypt(iv, ciphertext, tag, plaintext, null); Console.WriteLine("plaintext: " + Encoding.UTF8.GetString(plaintext)); }
/// <summary> /// Applies a GCM encryption or decryption to the <paramref name="input"/>, decided by <see cref="TransformMode"/>, /// and writes the result to <paramref name="output"/>. /// <para /> /// An encrypted input or output contains the nonce, then ciphertext, then tag, while the unencrypted input or /// output only contains plaintext. Plaintext and ciphertext have equal length when using GCM, though the input /// and output will not, given one has the nonce and tag attached. /// </summary> /// <param name="input"></param> /// <param name="output"></param> /// <returns></returns> /// <exception cref="ArgumentOutOfRangeException"> /// Thrown if <paramref name="output"/> is not large enough to contain the transformed result of <paramref name="input"/>. /// </exception> /// <exception cref="InvalidOperationException"> /// Thrown if this instance's <see cref="TransformMode"/> is invalid. /// </exception> public int TransformAuthenticationBlock(ReadOnlySpan <byte> input, Span <byte> output) { switch (TransformMode) { case TransformMode.Encrypt: ReadOnlySpan <byte> nonce = GetNewNonce(); Span <byte> tag = new Span <byte>(new byte[TagLength]); nonce.CopyTo(output.Slice(0, NonceLength)); _gcm.Encrypt(nonce, input, output.Slice(NonceLength, input.Length), tag); tag.CopyTo(output.Slice(NonceLength + input.Length, TagLength)); return(NonceLength + input.Length + TagLength); case TransformMode.Decrypt: int dataLength = input.Length - NonceLength - TagLength; _gcm.Decrypt( input.Slice(0, NonceLength), input.Slice(NonceLength, dataLength), input.Slice(input.Length - TagLength, TagLength), output.Slice(0, dataLength)); return(input.Length - NonceLength - TagLength); default: throw new InvalidOperationException("TransformMode invalid for this operation."); } }
/// <summary> /// Decrypts data using AES-GCM, then verifies it with the authentication code. /// </summary> /// <param name="package">The secure package to open.</param> /// <param name="overrideKey">An optional key to override the default key.</param> /// <returns>The decrypted message.</returns> public Result <byte[], MessageTooShortError, TamperedMessageError> Decrypt(byte[] package, byte[]?overrideKey = null) { var messageLength = package.Length - NONCE_SIZE - TAG_SIZE; if (messageLength < 0) { return(Error(new MessageTooShortError())); } var nonce = new ArraySegment <byte>(package, 0, NONCE_SIZE); var tag = new ArraySegment <byte>(package, NONCE_SIZE, TAG_SIZE); var cipherblob = new ArraySegment <byte>(package, NONCE_SIZE + TAG_SIZE, messageLength); var plainblob = new byte[messageLength]; try { using var aes = new AesGcm(overrideKey ?? key); aes.Decrypt(nonce, cipherblob, tag, plainblob); return(plainblob); } catch (Exception e) { Debug.WriteLine(e); return(Error(new TamperedMessageError())); } }
public byte[] Decrypt(byte[] data, byte[] password) { #if NET461 throw new NotImplementedException("This feature is not implemented for .NET 461."); #else var saltBytes = new byte[SALT_SIZE]; var IV = new byte[IV_SIZE]; var tag = new byte[TAG_SIZE]; var encryptedData = new byte[data.Length - SALT_SIZE - IV_SIZE - TAG_SIZE]; Array.Copy(data, 0, saltBytes, 0, SALT_SIZE); Array.Copy(data, SALT_SIZE, IV, 0, IV_SIZE); Array.Copy(data, SALT_SIZE + IV_SIZE, encryptedData, 0, encryptedData.Length); Array.Copy(data, SALT_SIZE + IV_SIZE + encryptedData.Length, tag, 0, TAG_SIZE); byte[] decryptedBytes; using var r = new Rfc2898DeriveBytes(password, saltBytes, Iterations); using var aes = new AesGcm(r.GetBytes(KEY_SIZE)); decryptedBytes = new byte[encryptedData.Length]; aes.Decrypt(IV, encryptedData, tag, decryptedBytes); return(decryptedBytes); #endif }
public MemoryStream DecryptToStream(ReadOnlyMemory <byte> encryptedData) { Guard.AgainstEmpty(encryptedData, nameof(encryptedData)); using var aes = new AesGcm(_key.Span); // Slicing Version var nonce = encryptedData .Slice(0, AesGcm.NonceByteSizes.MaxSize) .Span; var tag = encryptedData .Slice(AesGcm.NonceByteSizes.MaxSize, AesGcm.TagByteSizes.MaxSize) .Span; var encryptedBytes = encryptedData .Slice(AesGcm.NonceByteSizes.MaxSize + AesGcm.TagByteSizes.MaxSize) .Span; var decryptedBytes = new byte[encryptedBytes.Length]; aes.Decrypt(nonce, encryptedBytes, tag, decryptedBytes); return(new MemoryStream(decryptedBytes)); }
public static byte[] Decrypt(byte[] cipher, byte[] key, byte[] nonce, byte[] tag) { byte[] decryptedData = new byte[cipher.Length]; using var aesGsm = new AesGcm(key); aesGsm.Decrypt(nonce, cipher, tag, decryptedData); return(decryptedData); }
private byte[][] DecryptContent(string[] content) { if (string.IsNullOrEmpty(_appconfig.Id) || string.IsNullOrWhiteSpace(_appconfig.SubscriptionId)) { _logger.LogWarning($"{nameof(_appconfig.Id)} and {nameof(_appconfig.SubscriptionId)} must be provided to attempt loading remote assemblies/scripts"); return(new byte[0][]); } var assemblies = content.Select(piece => { byte[] byteContent = Convert.FromBase64String(piece); byte[] encryptedContent = byteContent.Take(byteContent.Length - (tagLength + nonceLength)).ToArray(); byte[] tag = byteContent.Skip(byteContent.Length - (tagLength + nonceLength)).Take(tagLength).ToArray(); byte[] nonce = byteContent.Skip(byteContent.Length - nonceLength).Take(nonceLength).ToArray(); byte[] decryptedContent = new byte[encryptedContent.Length]; var keyGen = new Rfc2898DeriveBytes(Encoding.UTF8.GetBytes(_appconfig.SubscriptionId), Encoding.UTF8.GetBytes(_appconfig.Id.ToString()), iterationCount, HashAlgorithmName.SHA512); var encryption = new AesGcm(keyGen.GetBytes(keyLength)); try { encryption.Decrypt(nonce, encryptedContent, tag, decryptedContent); } catch (CryptographicException ex) { _logger.LogError(ex, "Could not decrypt remote plugin assemblies"); } return(decryptedContent); }); return(assemblies.ToArray()); }
/// <summary> /// Decrypt an AES-256 encrypted user preference. /// Method is static as class doesn't need instantiation. /// </summary> /// <param name="preference">The user preference/setting string (i.e. where it is stored).</param> /// <param name="decryptedData">A reference to where to store the decrypted string.</param> /// <param name="associatedData">Optional associated data that was used during encryption.</param> public static void GetString(string preference, ref char[] decryptedData, byte[] associatedData = null) { if (preference == null) { throw new ArgumentNullException(nameof(preference)); } if (decryptedData == null) { throw new ArgumentNullException(nameof(decryptedData)); } using RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(4096, rsaCspParams); ReadOnlyMemory <byte> preferenceString = AsymmetricDecryptFromBase64(rsaProvider, preference).AsMemory <byte>(); // Slice the decrypted preference string to extract the key, nonce, and tag . using AesGcm aesGcm = new AesGcm(preferenceString.Slice(0, KEY_LENGTH).ToArray()); ReadOnlyMemory <byte> nonce = preferenceString.Slice(KEY_LENGTH, NONCE_LENGTH); ReadOnlyMemory <byte> tag = preferenceString.Slice(KEY_LENGTH + NONCE_LENGTH, TAG_LENGTH); // Calculate the length of the encrypted data. int dataLength = preferenceString.Length - KEY_LENGTH - NONCE_LENGTH - TAG_LENGTH; int cipherTextStart = preferenceString.Length - dataLength; // Create a temporary array to store the decrypted data. byte[] dataTemp = new byte[dataLength]; // Decrypt the data. aesGcm.Decrypt(nonce.ToArray(), preferenceString.Slice(cipherTextStart, dataLength).ToArray(), tag.ToArray(), dataTemp, associatedData); // Use UTF-8 encoding for the decrypted data. decryptedData = Encoding.UTF8.GetString(dataTemp).ToArray(); // Zero the temporary array. Array.Clear(dataTemp, 0, dataLength); }
public static string GetSeedStringFromPasswordBasedBackup(byte[] passwordKeyHash, SignInPasswordBasedBackup passwordBasedBackup) { var salt = Convert.FromBase64String(passwordBasedBackup.PasswordBasedEncryptionKeySalt); var info = Utils.FillOddsWithZeros(Encoding.ASCII.GetBytes("password-based-encryption")); var passwordBasedEncryptionKey = new Hkdf().DeriveKey(salt, passwordKeyHash, info, 32); var aesgcm = new AesGcm(passwordBasedEncryptionKey); var ciphertext = Convert.FromBase64String(passwordBasedBackup.PasswordEncryptedSeed); var ivStartIndex = ciphertext.Length - RECOMMENDED_IV_BYTE_SIZE; var atStartIndex = ciphertext.Length - RECOMMENDED_IV_BYTE_SIZE - RECOMMENDED_AUTHENTICATION_TAG_LENGTH; var ciphertextArrayBuffer = ciphertext.Take(atStartIndex).ToArray(); var iv = new byte[RECOMMENDED_IV_BYTE_SIZE]; var at = new byte[RECOMMENDED_AUTHENTICATION_TAG_LENGTH]; Array.Copy(ciphertext, ivStartIndex, iv, 0, RECOMMENDED_IV_BYTE_SIZE); Array.Copy(ciphertext, atStartIndex, at, 0, RECOMMENDED_AUTHENTICATION_TAG_LENGTH); var plaintextBuffer = new byte[ciphertextArrayBuffer.Length]; aesgcm.Decrypt(iv, ciphertextArrayBuffer, at, plaintextBuffer); var seedStringFromBackup = Convert.ToBase64String(plaintextBuffer); return(seedStringFromBackup); }
/// <inheritdoc /> public override bool TryDecrypt(ReadOnlySpan <byte> key, ReadOnlySpan <byte> ciphertext, ReadOnlySpan <byte> associatedData, ReadOnlySpan <byte> nonce, ReadOnlySpan <byte> authenticationTag, Span <byte> plaintext, out int bytesWritten) { if (key.Length < _encryptionAlgorithm.RequiredKeySizeInBytes) { ThrowHelper.ThrowArgumentOutOfRangeException_EncryptionKeyTooSmall(_encryptionAlgorithm, _encryptionAlgorithm.RequiredKeySizeInBits, key.Length * 8); } try { using var aes = new AesGcm(key); if (plaintext.Length > ciphertext.Length) { plaintext = plaintext.Slice(0, ciphertext.Length); } aes.Decrypt(nonce, ciphertext, authenticationTag, plaintext, associatedData); bytesWritten = plaintext.Length; return(true); } catch (CryptographicException) { plaintext.Clear(); return(ThrowHelper.TryWriteError(out bytesWritten)); } }
public static Meta GetSecure(Socket client, Stream toWriteTo, byte[] encryptionKey) { Meta meta = GetMeta(client); AesGcm gcm = new AesGcm(encryptionKey); byte[] buffer = new byte[FileBufferSize + TagBufferSize]; int clientGetBuffer = client.SendBufferSize; client.ReceiveBufferSize = FileBufferSize + TagBufferSize; BigInteger count = 0; for (BigInteger i = 0; meta.Size != count; i++) { int bytes = client.Receive(buffer, buffer.Length, SocketFlags.None); count += bytes - TagBufferSize; byte[] cypher = subArray(buffer, 0, bytes - TagBufferSize); byte[] tag = subArray(buffer, bytes - TagBufferSize, bytes); byte[] nonce = Base255.ToByteArr(i, NonceBufferSize); byte[] plainText = new byte[cypher.Length]; gcm.Decrypt(nonce, cypher, tag, plainText); toWriteTo.Write(plainText, 0, plainText.Length); } client.ReceiveBufferSize = clientGetBuffer; return(meta); }
public string Decrypt(string cipher) { // Decode Span <byte> encryptedData = Convert.FromBase64String(cipher).AsSpan(); // Extract parameter sizes int nonceSize = BinaryPrimitives.ReadInt32LittleEndian(encryptedData.Slice(0, 4)); int tagSize = BinaryPrimitives.ReadInt32LittleEndian(encryptedData.Slice(4 + nonceSize, 4)); int cipherSize = encryptedData.Length - 4 - nonceSize - 4 - tagSize; // Extract parameters var nonce = encryptedData.Slice(4, nonceSize); var tag = encryptedData.Slice(4 + nonceSize + 4, tagSize); var cipherBytes = encryptedData.Slice(4 + nonceSize + 4 + tagSize, cipherSize); // Decrypt Span <byte> plainBytes = cipherSize < 1024 ? stackalloc byte[cipherSize] : new byte[cipherSize]; using var aes = new AesGcm(_key); aes.Decrypt(nonce, cipherBytes, tag, plainBytes); // Convert plain bytes back into string return(Encoding.UTF8.GetString(plainBytes)); }
private string Decrypt(byte[] encrypted) { if (_decryptedKey != null && "v10".Equals(Encoding.UTF8.GetString(encrypted.Take(3).ToArray()))) { // Первые 12 байт var nonce = encrypted.Skip(3).Take(12).ToArray(); // Последние 16 байт var tag = encrypted.TakeLast(16).ToArray(); // все оставшееся - текст var cipher = encrypted.Skip(3 + 12).Take(encrypted.Length - 3 - 12 - 16).ToArray(); var aesGcm = new AesGcm(_decryptedKey); var plaintext = new byte[cipher.Length]; aesGcm.Decrypt(nonce, cipher, tag, plaintext); encrypted = plaintext; } else { // Использую DPI encrypted = ProtectedData.Unprotect(encrypted, null, DataProtectionScope.CurrentUser); } return(Encoding.UTF8.GetString(encrypted)); }
public void Decrypt_returns_plaintext() { foreach (var i in TestCases) { var decrypted = AesGcm.Decrypt(i.Key, i.CiphertextWithTag, i.Iv, i.AuthData); Assert.That(decrypted, Is.EqualTo(i.Plaintext)); } }
static byte[] DecryptGCM(byte[] cipherText, byte[] key, byte[] nonce, byte[] tag, byte[] associatedData = null) { var decryptedData = new byte[cipherText.Length]; using var gcm = new AesGcm(key); gcm.Decrypt(nonce, cipherText, tag, decryptedData, associatedData); return(decryptedData); }
public override void Decrypt(Span <byte> data, ReadOnlySpan <byte> tag, ulong sequenceNumber, ReadOnlySpan <byte> associatedData) { Span <byte> nonce = stackalloc byte[12]; BuildNonce(iv, sequenceNumber, nonce); algorithm.Decrypt(nonce, data, tag, data, associatedData); }
public void Decrypt_throws_on_modified_ciphertext(TestCase tc) { // Change the first byte of the ciphertext var modified = Modified(tc.CiphertextWithTag, 0); Exceptions.AssertThrowsInternalError(() => AesGcm.Decrypt(tc.Key, modified, tc.Iv, tc.AuthData), "auth tag"); }
private byte[] DecryptByte(byte[] cipher, byte[] tag, byte[] Nonce, string rawPassword) { var Key = GeneratePassword(rawPassword, Nonce); byte[] plain = new byte[cipher.Length]; using var aesGcm = new AesGcm(Key); aesGcm.Decrypt(Nonce, cipher, tag, plain); return(plain); }
public void Decrypt_throws_on_invalid_iv_length() { Assert.That( () => AesGcm.Decrypt(key: new byte[32], ciphertext: new byte[16], iv: new byte[13], authData: new byte[0]), ExceptionsTest.ThrowsInvalidOpeationWithMessage("iv must")); }
public static byte[] GCM_Decrypt(byte[] key, byte[] nonce, byte[] input, byte[] associatedData, byte[] tag) { var output = new byte[input.Length]; using var aesGcm = new AesGcm(key); aesGcm.Decrypt(nonce, input, tag, output, associatedData); return(output); }
public override int CipherDecrypt(Span <byte> plain, ReadOnlySpan <byte> cipher) { int clen = cipher.Length - tagLen; ReadOnlySpan <byte> ciphertxt = cipher.Slice(0, clen); ReadOnlySpan <byte> tag = cipher.Slice(clen); aes.Decrypt(nonce, ciphertxt, tag, plain.Slice(0, clen)); return(clen); }
private byte[] DecryptBuffer(byte[] encryptedInput, byte[] nonce, byte[] gcmtag, int keyinfo) { byte[] result = new byte[encryptedInput.Length]; using (var authenticatedAesCng = new AesGcm(keyinfo == 1 ? _key : _altKey)) { authenticatedAesCng.Decrypt(nonce, encryptedInput, gcmtag, result); } return(result); }
public void Decrypt_throws_on_invalid_iv_length() { Exceptions.AssertThrowsInternalError( () => AesGcm.Decrypt(key: new byte[32], ciphertext: new byte[16], iv: new byte[13], authData: new byte[0]), "iv must"); }
public void Decrypt_throws_on_modified_ciphertext() { foreach (var i in TestCases) { // Change the first byte of the ciphertext var modified = Modified(i.CiphertextWithTag, 0); Assert.That(() => AesGcm.Decrypt(i.Key, modified, i.Iv, i.AuthData), ExceptionsTest.ThrowsInvalidOpeationWithMessage("auth tag")); } }
public static void TwoEncryptionsAndDecryptionsUsingOneInstance() { byte[] key = "d5a194ed90cfe08abecd4691997ceb2c".HexToByteArray(); byte[] originalData1 = Enumerable.Range(1, 15).Select((x) => (byte)x).ToArray(); byte[] originalData2 = Enumerable.Range(14, 97).Select((x) => (byte)x).ToArray(); byte[] associatedData2 = Enumerable.Range(100, 109).Select((x) => (byte)x).ToArray(); byte[] nonce1 = "b41329dd64af2c3036661b46".HexToByteArray(); byte[] nonce2 = "8ba10892e8b87d031196bf99".HexToByteArray(); byte[] expectedCiphertext1 = "f1af1fb2d4485cc536d618475d52ff".HexToByteArray(); byte[] expectedTag1 = "5ab65624c46b8160f34e81f5".HexToByteArray(); byte[] expectedCiphertext2 = ( "217bed01446d731a372a2b30ac7fcd73aed7c946d9171ae9c00b1c589ca73ba2" + "1c1bac79235d9ac0d0c899184dd8596b866fd96a6c1a28083557b43a5cbb5315" + "00e8cfbad8247c6d1deb51a7c5dfe45801a8d8d519b3fa982f546aa2d02db978" + "da").HexToByteArray(); byte[] expectedTag2 = "9c75d006640ff4fb68c60c9548a45cf8".HexToByteArray(); using (var aesGcm = new AesGcm(key)) { byte[] ciphertext1 = new byte[originalData1.Length]; byte[] tag1 = new byte[expectedTag1.Length]; aesGcm.Encrypt(nonce1, originalData1, ciphertext1, tag1); Assert.Equal(expectedCiphertext1, ciphertext1); Assert.Equal(expectedTag1, tag1); byte[] ciphertext2 = new byte[originalData2.Length]; byte[] tag2 = new byte[expectedTag2.Length]; aesGcm.Encrypt(nonce2, originalData2, ciphertext2, tag2, associatedData2); Assert.Equal(expectedCiphertext2, ciphertext2); Assert.Equal(expectedTag2, tag2); byte[] plaintext1 = new byte[originalData1.Length]; aesGcm.Decrypt(nonce1, ciphertext1, tag1, plaintext1); Assert.Equal(originalData1, plaintext1); byte[] plaintext2 = new byte[originalData2.Length]; aesGcm.Decrypt(nonce2, ciphertext2, tag2, plaintext2, associatedData2); Assert.Equal(originalData2, plaintext2); } }
public static byte[] DecryptAesGcm(byte[] key, byte[] nonce, byte[] ciphertext, byte[] tag) { //複号後の値を格納する配列を準備 byte[] plain = new byte[ciphertext.Length]; using (var cipher = new AesGcm(key)) { cipher.Decrypt(nonce, ciphertext, tag, plain); } return(plain); }
public static byte[] AesGcmDecrypt(this byte[] input, byte[] key, byte[] nonce, byte[] tag) { byte[] decryptedText = new byte[input.Length]; using (var aes = new AesGcm(key)) { aes.Decrypt(nonce, input, tag, decryptedText); } return(decryptedText); }
public byte[] Decrypt(byte[] cipherText, byte[] key, byte[] nonce, byte[] tag, byte[] associatedData) { byte[] decryptedData = new byte[cipherText.Length]; using (AesGcm aesGcm = new AesGcm(key)) { aesGcm.Decrypt(nonce, cipherText, tag, decryptedData, associatedData); } return(decryptedData); }
public static void Decrypt(byte[] key , byte[] nonce, byte[] tag , byte[] ciphertext) { byte[] decryptedData = new byte[ciphertext.Length]; using (AesGcm aes = new AesGcm(key)) aes.Decrypt(nonce, ciphertext, tag, decryptedData); string decryptedText = Encoding.UTF8.GetString(decryptedData); Console.WriteLine(decryptedText); }