示例#1
0
        /// <summary>
        /// Encrypt given bytes
        /// </summary>
        /// <param name="toEncrypt"></param>
        /// <param name="key"></param>
        /// <param name="associatedData"></param>
        /// <returns></returns>
        public static byte[] Encrypt(byte[] toEncrypt, byte[] key, byte[] associatedData = null)
        {
            byte[] tag        = new byte[KEY_BYTES];
            byte[] nonce      = new byte[NONCE_BYTES];
            byte[] cipherText = new byte[toEncrypt.Length];

            using (var cipher = new AesGcm(key))
            {
                cipher.Encrypt(nonce, toEncrypt, cipherText, tag, associatedData);

                return(Concat(tag, Concat(nonce, cipherText)));
            }
        }
示例#2
0
        public static void EncryptDecryptNullNonce()
        {
            byte[] key        = "d5a194ed90cfe08abecd4691997ceb2c".HexToByteArray();
            byte[] plaintext  = new byte[0];
            byte[] ciphertext = new byte[0];
            byte[] tag        = new byte[16];

            using (var aesGcm = new AesGcm(key))
            {
                Assert.Throws <ArgumentNullException>(() => aesGcm.Encrypt((byte[])null, plaintext, ciphertext, tag));
                Assert.Throws <ArgumentNullException>(() => aesGcm.Decrypt((byte[])null, ciphertext, tag, plaintext));
            }
        }
示例#3
0
        public (byte[], byte[]) Encrypt(byte[] dataToEncrypt, byte[] key, byte[] nonce, byte[] associatedData)
        {
            // these will be filled during the encryption
            byte[] tag        = new byte[16];
            byte[] ciphertext = new byte[dataToEncrypt.Length];

            using (AesGcm aesGcm = new AesGcm(key))
            {
                aesGcm.Encrypt(nonce, dataToEncrypt, ciphertext, tag, associatedData);
            }

            return(ciphertext, tag);
        }
        public int Encrypt(byte[] plainText, int plainTextLength, byte[] cipherTextBuffer, ulong recordSequenceNumber)
        {
            Span <byte> cipherTextBufferSpan = cipherTextBuffer.AsSpan();

            _aesGcmCipher.Encrypt(
                Aes128GcmHelper.XorNonce(_nonceInfoParameterHash, recordSequenceNumber).AsSpan(),
                plainText.AsSpan().Slice(0, plainTextLength),
                cipherTextBufferSpan.Slice(0, plainTextLength),
                cipherTextBufferSpan.Slice(plainTextLength, Aes128GcmHelper.CONTENT_ENCRYPTION_KEY_LENGTH)
                );

            return(plainTextLength + Aes128GcmHelper.CONTENT_ENCRYPTION_KEY_LENGTH);
        }
        public static (byte[] ciphertext, byte[] tag) ComputeHash(byte[] key, byte[] nonce, byte[] aadBytes)
        {
            using (var aes = new AesGcm(key))
            {
                var plaintextBytes = Encoding.UTF8.GetBytes("");
                var ciphertext     = new byte[plaintextBytes.Length];
                var tag            = new byte[AesGcm.TagByteSizes.MaxSize]; // MaxSize = 16

                aes.Encrypt(nonce, plaintextBytes, ciphertext, tag, aadBytes);

                return(ciphertext, tag);
            }
        }
示例#6
0
        static (byte[] ciphertext, byte[] mac) EncryptStringToBytesAsync(string plainText, string context, byte[] key, byte[] iv)
        {
            var dataToEncrypt  = Encoding.UTF8.GetBytes(plainText);
            var associatedData = Encoding.UTF8.GetBytes(context);
            var mac            = new byte[16];
            var encrypted      = new byte[dataToEncrypt.Length];

            using (var aes = new AesGcm(key))
            {
                aes.Encrypt(iv, dataToEncrypt, encrypted, mac, associatedData);
            }

            return(encrypted, mac);
        }
示例#7
0
        public static void PlaintextAndCiphertextSizeDiffer(int ptLen, int ctLen)
        {
            byte[] key        = new byte[16];
            byte[] nonce      = new byte[12];
            byte[] plaintext  = new byte[ptLen];
            byte[] ciphertext = new byte[ctLen];
            byte[] tag        = new byte[16];

            using (var aesGcm = new AesGcm(key))
            {
                Assert.Throws <ArgumentException>(() => aesGcm.Encrypt(nonce, plaintext, ciphertext, tag));
                Assert.Throws <ArgumentException>(() => aesGcm.Decrypt(nonce, ciphertext, tag, plaintext));
            }
        }
示例#8
0
        public void Encrypt()
        {
            //given
            byte[] iv   = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
            byte[] aad  = Encoding.UTF8.GetBytes("secre");
            byte[] text = Encoding.UTF8.GetBytes("hellow aes !");

            //when
            byte[][] test = AesGcm.Encrypt(aes128Key, iv, aad, text);

            //then
            Assert.Equal(test[0], new byte[] { 245, 242, 160, 166, 250, 62, 102, 211, 158, 42, 62, 73 });
            Assert.Equal(test[1], new byte[] { 195, 69, 216, 140, 118, 58, 48, 131, 47, 225, 205, 198, 78, 12, 180, 76 });
        }
示例#9
0
        public static byte[] Encrypt(out byte[] key, out byte[] nonce, out byte[] tag, byte[] dataToEncrypt)
        {
            key   = new byte[16];
            nonce = new byte[12];
            RandomNumberGenerator.Fill(key);
            RandomNumberGenerator.Fill(nonce);

            tag = new byte[16];
            byte[] ciphertext = new byte[dataToEncrypt.Length];

            using (AesGcm aes = new AesGcm(key))
                aes.Encrypt(nonce, dataToEncrypt, ciphertext, tag);

            return(ciphertext);
        }
示例#10
0
        public static void AesGcmNistTests(AEADTest testCase)
        {
            using (var aesGcm = new AesGcm(testCase.Key))
            {
                byte[] ciphertext = new byte[testCase.Plaintext.Length];
                byte[] tag        = new byte[testCase.Tag.Length];
                aesGcm.Encrypt(testCase.Nonce, testCase.Plaintext, ciphertext, tag, testCase.AssociatedData);
                Assert.Equal(testCase.Ciphertext, ciphertext);
                Assert.Equal(testCase.Tag, tag);

                byte[] plaintext = new byte[testCase.Plaintext.Length];
                aesGcm.Decrypt(testCase.Nonce, ciphertext, tag, plaintext, testCase.AssociatedData);
                Assert.Equal(testCase.Plaintext, plaintext);
            }
        }
        /// <summary>
        /// Stores a user preference encrypted using AES-256.
        /// Method is not static to ensure an instance of the class (and a new AES key) is created.
        /// </summary>
        /// <param name="preference">The user preference/setting string (i.e. where to store it).</param>
        /// <param name="secret">A reference to the data to store. The original data should be zeroed out by this method.</param>
        /// <param name="associatedData">Optional associated data. It will need to be stored separately.</param>
        /// <returns>True on success.</returns>
        public bool StoreString(ref string preference, ref char[] secret, byte[] associatedData = null)
        {
            if (secret == null)
            {
                throw new ArgumentNullException(nameof(secret));
            }

            // This is not a static method.
            // The only way to store a new password is by creating an instance of the class, which creates a new AES key.
            using RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(4096, rsaCspParams);
            Span <byte> aesKey = AsymmetricDecryptFromBase64(rsaProvider, rsaEncryptedAesKey);

            // NIST recommends only using a 12-byte/96-bit nonce for AES-GCM. It shouldn't be reused.
            byte[] nonce = new byte[NONCE_LENGTH];
            rngCsp.GetBytes(nonce);
            // Note: Associated data that is passed in on encryption must also be passed in for decryption. Default is null.
            //        This data will not be stored with the other data needed to decrypt the message.
            // AES-GCM generates output that is the same length as input.
            byte[] cipherText = new byte[secret.Length];
            // AES-GCM generated tag can be truncated, but its full size is 16-byte/128-bit.
            byte[] tag = new byte[TAG_LENGTH];

            using AesGcm aesGcm = new AesGcm(aesKey);
            // Use UTF-8 Encoding for the secret.
            aesGcm.Encrypt(nonce, Encoding.UTF8.GetBytes(secret), cipherText, tag, associatedData);
            // Store the length of the original secret, and then wipe the data.
            int secretLength = secret.Length;

            Array.Clear(secret, 0, secretLength);

            // Create a user preference string. The key, nonce, associated data, tag, and cipher text are needed to decrypt.
            // Format: Base64(RsaEncrypt(concat(key, nonce, tag, cipherText)))
            // Zero out each array once it is no longer needed.
            byte[] preferenceString = new byte[secretLength + KEY_LENGTH + NONCE_LENGTH + TAG_LENGTH];
            Buffer.BlockCopy(aesKey.ToArray(), 0, preferenceString, 0, aesKey.Length);
            aesKey.Clear();
            Buffer.BlockCopy(nonce, 0, preferenceString, KEY_LENGTH, NONCE_LENGTH);
            Array.Clear(nonce, 0, NONCE_LENGTH);
            Buffer.BlockCopy(tag, 0, preferenceString, KEY_LENGTH + NONCE_LENGTH, TAG_LENGTH);
            Array.Clear(tag, 0, TAG_LENGTH);
            Buffer.BlockCopy(cipherText, 0, preferenceString, KEY_LENGTH + NONCE_LENGTH + TAG_LENGTH, cipherText.Length);
            Array.Clear(cipherText, 0, cipherText.Length);

            preference = AsymmetricEncryptToBase64(rsaProvider, preferenceString);

            // TODO: Return false on failure.
            return(true);
        }
示例#12
0
        /// <inheritdoc />
        public EncryptedPacket Encrypt(ReadOnlySpan <byte> plainText, ReadOnlySpan <byte> key, ReadOnlySpan <byte> optionalAssociatedData = default)
        {
            ArgCheck.NotEmpty(plainText, nameof(plainText));
            ArgCheck.HasLength(this.AlgorithmProperties.KeySizeInBytes, key, nameof(key));

            var iv = CryptoHelpers.GetRandomBytes(this.AlgorithmProperties.IvSizeInBytes);

            // Containers to hold crypto operation outputs.
            var cipherText = new byte[plainText.Length];
            var authTag    = new byte[this.AlgorithmProperties.AuthTagSizeInBytes];

            using var algo = new AesGcm(key);
            algo.Encrypt(iv, plainText, cipherText, authTag, optionalAssociatedData);

            return(EncryptedPacketExtensions.CreateNewEncryptedPacket(cipherText, iv, authTag));
        }
示例#13
0
        /// <inheritdoc />
        public override void Encrypt(ReadOnlySpan <byte> key, ReadOnlySpan <byte> plaintext, ReadOnlySpan <byte> nonce, ReadOnlySpan <byte> associatedData, Span <byte> ciphertext, Span <byte> authenticationTag, out int authenticationTagBytesWritten)
        {
            if (key.Length < _encryptionAlgorithm.RequiredKeySizeInBytes)
            {
                ThrowHelper.ThrowArgumentOutOfRangeException_EncryptionKeyTooSmall(_encryptionAlgorithm, _encryptionAlgorithm.RequiredKeySizeInBytes << 3, key.Length << 8);
            }

            using var aes = new AesGcm(key);
            if (ciphertext.Length > plaintext.Length)
            {
                ciphertext = ciphertext.Slice(0, plaintext.Length);
            }

            aes.Encrypt(nonce, plaintext, ciphertext, authenticationTag, associatedData);
            authenticationTagBytesWritten = authenticationTag.Length;
        }
示例#14
0
        public byte[][] Encrypt(byte[] aad, byte[] plainText, byte[] cek)
        {
            Ensure.BitSize(cek, keyLength, string.Format("AES-GCM algorithm expected key of size {0} bits, but was given {1} bits", keyLength, cek.Length * 8L));

            byte[] iv = Arrays.Random(96);

            try
            {
                byte[][] cipherAndTag = AesGcm.Encrypt(cek, iv, aad, plainText);

                return(new[] { iv, cipherAndTag[0], cipherAndTag[1] });
            }
            catch (CryptographicException e)
            {
                throw new EncryptionException("Unable to encrypt content.", e);
            }
        }
示例#15
0
        public static byte[] Encrypt(byte[] encryptionKey, byte[] seed)
        {
            var iv         = Utils.GenerateRandom(RECOMMENDED_IV_BYTE_SIZE);
            var at         = new byte[RECOMMENDED_AUTHENTICATION_TAG_LENGTH];
            var ciphertext = new byte[seed.Length];

            using var aesGcm = new AesGcm(encryptionKey);
            aesGcm.Encrypt(iv, seed, ciphertext, at);

            var result = new byte[ciphertext.Length + at.Length + iv.Length];

            Array.Copy(ciphertext, result, ciphertext.Length);
            Array.Copy(at, 0, result, ciphertext.Length, RECOMMENDED_AUTHENTICATION_TAG_LENGTH);
            Array.Copy(iv, 0, result, ciphertext.Length + RECOMMENDED_AUTHENTICATION_TAG_LENGTH, RECOMMENDED_IV_BYTE_SIZE);

            return(result);
        }
示例#16
0
        public static void InvalidNonceSize(int nonceSize)
        {
            int dataLength = 30;

            byte[] plaintext  = Enumerable.Range(1, dataLength).Select((x) => (byte)x).ToArray();
            byte[] ciphertext = new byte[dataLength];
            byte[] key        = new byte[16];
            byte[] nonce      = new byte[nonceSize];
            byte[] tag        = new byte[AesGcm.TagByteSizes.MinSize];
            RandomNumberGenerator.Fill(key);
            RandomNumberGenerator.Fill(nonce);

            using (var aesGcm = new AesGcm(key))
            {
                Assert.Throws <ArgumentException>("nonce", () => aesGcm.Encrypt(nonce, plaintext, ciphertext, tag));
            }
        }
        // GCM mode (preferred)
        public static byte[] EncryptWithGCM(byte[] data, byte[] key)
        {
            byte[] tag        = new byte[GCM_KEY_SIZE / 8];
            byte[] nonce      = CreateRandomBytes(GCM_NONCE_SIZE);
            byte[] cipherText = new byte[data.Length];

            byte[] completeCipherText = new byte[tag.Length + nonce.Length + cipherText.Length];

            using (var cipher = new AesGcm(key))
            {
                cipher.Encrypt(nonce, data, cipherText, tag);

                Array.Copy(tag, completeCipherText, tag.Length);
                Array.Copy(nonce, 0, completeCipherText, tag.Length, nonce.Length);
                Array.Copy(cipherText, 0, completeCipherText, tag.Length + nonce.Length, cipherText.Length);
                return(completeCipherText);
            }
        }
示例#18
0
        public static void InplaceEncryptDecrypt()
        {
            byte[] key               = "d5a194ed90cfe08abecd4691997ceb2c".HexToByteArray();
            byte[] nonce             = new byte[12];
            byte[] originalPlaintext = new byte[] { 1, 2, 8, 12, 16, 99, 0 };
            byte[] data              = (byte[])originalPlaintext.Clone();
            byte[] tag               = new byte[16];
            RandomNumberGenerator.Fill(nonce);

            using (var aesGcm = new AesGcm(key))
            {
                aesGcm.Encrypt(nonce, data, data, tag);
                Assert.NotEqual(originalPlaintext, data);

                aesGcm.Decrypt(nonce, data, tag, data);
                Assert.Equal(originalPlaintext, data);
            }
        }
示例#19
0
        public static string Encrypt(JweConfig config, String payload, JweHeader header)
        {
            byte[] cek = AesEncryption.GenerateCek(256);
            byte[] encryptedSecretKeyBytes = RsaEncryption.WrapSecretKey(config.EncryptionCertificate.GetRSAPublicKey(), cek, "SHA-256");
            string encryptedKey            = Base64Utils.URLEncode(encryptedSecretKeyBytes);

            byte[] iv           = AesEncryption.GenerateIV();
            byte[] payloadBytes = Encoding.UTF8.GetBytes(payload);

            string headerString  = header.Json.ToString();
            string encodedHeader = Base64Utils.URLEncode(Encoding.UTF8.GetBytes(headerString));

            byte[] aad = Encoding.ASCII.GetBytes(encodedHeader);

            var encrypted = AesGcm.Encrypt(cek, iv, payloadBytes, aad);

            return(Serialize(encodedHeader, encryptedKey, Base64Utils.URLEncode(iv), Base64Utils.URLEncode(encrypted.Ciphertext), Base64Utils.URLEncode(encrypted.AuthTag)));
        }
示例#20
0
    /// <summary>
    /// Encrypts the provided message. (For EVN this actually decrypts the message)
    /// </summary>
    /// <param name="HEXMessage">Message to encrypt</param>
    /// <returns></returns>
    public string Encrypt(string HEXMessage)
    {
        string message = HEXMessage.Replace(" ", "");

        byte[] plainText  = HexToByteArray(message.Substring(HeaderLength, message.Length - HeaderLength - END_LENGTH));
        byte[] ciphertext = new byte[plainText.Length];
        byte[] nonce      = HexToByteArray(message.Substring(METER_LENGTH, SYSTEM_TITLE_LENGTH) + message.Substring(METER_LENGTH + SYSTEM_TITLE_LENGTH + SECURITY_LENGTH, FRAME_COUNTER_LENGTH));
        using (AesGcm aesGcm = new AesGcm(KEY))
        {
            aesGcm.Encrypt(
                nonce,
                plainText,
                ciphertext,
                TAG);
        }

        return(GXCommon.ToHex(ciphertext));
    }
示例#21
0
 protected override SmartBuffer EncryptChunk(ReadOnlyMemory <byte> raw, ReadOnlySpan <byte> key, ReadOnlySpan <byte> nonce, ReadOnlySpan <byte> aad = default)
 {
     using (var aes = new AesGcm(key))
     {
         SmartBuffer cipherPacket = SmartBuffer.Rent(raw.Length + LEN_TAG);
         var         cipherSpan   = cipherPacket.Memory.Span;
         try
         {
             aes.Encrypt(nonce, raw.Span, cipherSpan.Slice(0, raw.Length), cipherSpan.Slice(raw.Length, LEN_TAG), aad);
             cipherPacket.SignificantLength = raw.Length + LEN_TAG;
         }
         catch (Exception ex)
         {
             cipherPacket.SignificantLength = 0;
             _logger?.LogWarning($"AeadAesGcm EncryptChunk failed. {ex.Message}");
         }
         return(cipherPacket);
     }
 }
        public static byte[] Encrypt(byte[] plainData, byte[] key)
        {
            var aes   = new AesGcm(key);
            var nonce = Encoding.UTF8.GetBytes(BitConverter.ToString(key).GetHashCode().ToString());

            byte[] cipherData = new byte[16 * (plainData.Length / 16 + 1)];
            byte[] tag        = new byte[AesGcm.TagByteSizes.MaxSize];
            aes.Encrypt(nonce, plainData, cipherData, tag);
            aes.Dispose();
            using var stream = new MemoryStream();
            stream.Write(cipherData, 0, cipherData.Length);
            stream.Write(DataTagSeperator, 0, DataTagSeperator.Length);
            stream.Write(tag, 0, tag.Length);
            stream.Write(TagNonceSeperator, 0, TagNonceSeperator.Length);
            stream.Write(nonce, 0, nonce.Length);
            byte[] r = stream.ToArray();
            stream.Close();
            return(r);
        }
示例#23
0
        public static void AesGcmNistTestsTamperCiphertext(AEADTest testCase)
        {
            using (var aesGcm = new AesGcm(testCase.Key))
            {
                byte[] ciphertext = new byte[testCase.Plaintext.Length];
                byte[] tag        = new byte[testCase.Tag.Length];
                aesGcm.Encrypt(testCase.Nonce, testCase.Plaintext, ciphertext, tag, testCase.AssociatedData);
                Assert.Equal(testCase.Ciphertext, ciphertext);
                Assert.Equal(testCase.Tag, tag);

                ciphertext[0] ^= 1;

                byte[] plaintext = new byte[testCase.Plaintext.Length];
                RandomNumberGenerator.Fill(plaintext);
                Assert.Throws <CryptographicException>(
                    () => aesGcm.Decrypt(testCase.Nonce, ciphertext, tag, plaintext, testCase.AssociatedData));
                Assert.Equal(new byte[plaintext.Length], plaintext);
            }
        }
示例#24
0
        public byte[] Encrypt(byte[] plaintext, out byte[] tag)
        {
            CheckDisposed();
            if (plaintext == null)
            {
                throw new ArgumentNullException(nameof(plaintext));
            }

            byte[] plaintextDup = (byte[])plaintext.Clone();
            Utils.ShuffleEndianess(plaintextDup);

            byte[] ciphertext = new byte[plaintext.Length];
            tag = new byte[16];
            aes.Encrypt(iv, plaintextDup, ciphertext, tag);

            Utils.ShuffleEndianess(ciphertext);
            Utils.ShuffleEndianess(tag);
            return(ciphertext);
        }
示例#25
0
        public static void Encrypt(ReadOnlySpan <byte> key, ReadOnlySpan <byte> plain, ref Span <char> token)
        {
            Span <byte> data   = stackalloc byte[TagSize + NonceSize + plain.Length];
            var         tag    = data.Slice(0, TagSize);
            var         nonce  = data.Slice(TagSize, NonceSize);
            var         cipher = data.Slice(TagSize + NonceSize);

            RandomNumberGenerator.Fill(nonce);

            using var aes = new AesGcm(key);
            aes.Encrypt(nonce, plain, cipher, tag);

            if (!Convert.TryToBase64Chars(data, token, out var chars))
            {
                throw new Exception("Token is too short");
            }

            token = token.Slice(0, chars);
        }
示例#26
0
    static string aesGcmPbkdf2EncryptToBase64(string password, string data)
    {
        int PBKDF2_ITERATIONS = 15000;

        byte[] salt = GenerateSalt32Byte();
        byte[] key  = new byte[32];
        using (var deriveBytes = new Rfc2898DeriveBytes(password, salt, PBKDF2_ITERATIONS, HashAlgorithmName.SHA256)) {
            key = deriveBytes.GetBytes(32);
        }
        byte[] plaintext      = Encoding.UTF8.GetBytes(data);
        byte[] gcmTag         = new byte[16];
        byte[] nonce          = GenerateRandomNonce();
        byte[] cipherText     = new byte[plaintext.Length];
        byte[] associatedData = new byte[0];
        using (var cipher = new AesGcm(key)) {
            cipher.Encrypt(nonce, plaintext, cipherText, gcmTag, associatedData);
            return(Base64Encoding(salt) + ":" + Base64Encoding(nonce) + ":" + Base64Encoding(cipherText) + ":" + Base64Encoding(gcmTag));
        }
    }
        public static (string, string, string) Encrypt(string str, byte[] key)
        {
            using (var aes = new AesGcm(key))
            {
                var nonce = new byte[AesGcm.NonceByteSizes.MaxSize];
                RandomNumberGenerator.Fill(nonce);

                var tag = new byte[AesGcm.TagByteSizes.MaxSize];
                RandomNumberGenerator.Fill(tag);

                var textBytes  = ToBytes(str);
                var cipherText = new byte[textBytes.Length];

                aes.Encrypt(nonce, textBytes, cipherText, tag);

                return(Convert.ToBase64String(cipherText),
                       Convert.ToBase64String(nonce), Convert.ToBase64String(tag));
            }
        }
示例#28
0
        public override void Initialize()
        {
            aesNonce = new byte[12];
            aesKey   = new byte[32];

            RandomNumberGenerator.Fill(aesNonce);
            RandomNumberGenerator.Fill(aesKey);

            var tasks = new Task[options.Threads];

            for (var i = 0; i < options.Threads; i++)
            {
                var i1 = i;

                tasks[i1] = Task.Run(() =>
                {
                    var data  = Encoding.UTF8.GetBytes(DataGenerator.GenerateString((int)(volume / options.Threads)));
                    var rand  = new Random();
                    sha512Key = new byte[64];

                    for (var j = 0; j < 64; j++)
                    {
                        sha512Key[j] = (byte)rand.Next();
                    }

                    var hmac = new HMACSHA512(sha512Key);
                    hmac.Initialize();

                    datasSHA[i1] = Encoding.Default.GetString(hmac.ComputeHash(data));

                    datasAES[i1] = new byte[data.Length];

                    using var aes = new AesGcm(aesKey);
                    aesTag[i1]    = new byte[16];

                    aes.Encrypt(aesNonce, data, datasAES[i1], aesTag[i1]);
                });
            }

            Task.WaitAll(tasks);
            GC.Collect();
        }
示例#29
0
		public void GlobalSetup()
		{
			key = new byte[32];
			nonce = new byte[12];
			plaintext = new byte[Size];
			ciphertext = new byte[Size];
			tag = new byte[16];
			empty = new byte[0];

			ciphertextGcm = new byte[Size];
			ciphertextSiv = new byte[Size];
			tagGcm = new byte[16];
			tagSiv = new byte[16];

			gcm = new AesGcm(key);
			siv = new AesGcmSiv(key);

			gcm.Encrypt(nonce, plaintext, ciphertextGcm, tagGcm);
			siv.Encrypt(nonce, plaintext, ciphertextSiv, tagSiv);
		}
示例#30
0
        public static void SendSecure(Socket client, Meta meta, Stream data, byte[] encryptionKey)
        {
            SendMeta(client, meta);

            AesGcm gcm = new AesGcm(encryptionKey);

            byte[] buffer           = new byte[FileBufferSize];
            int    clientSendBuffer = client.SendBufferSize;

            client.SendBufferSize = FileBufferSize + TagBufferSize;

            BigInteger count = 0;

            for (BigInteger i = 0; count != meta.Size; i++)
            {
                int bytes = data.Read(buffer, 0, buffer.Length);
                count += bytes;
                logger.Log($"[{i}] Count: {count}", LoggerState.Debug);
                if (bytes != buffer.Length)
                {
                    Array.Resize(ref buffer, bytes);
                }

                byte[] tag        = new byte[16];
                byte[] cyphertext = new byte[buffer.Length];

                byte[] nonce = Base255.ToByteArr(i, NonceBufferSize);

                gcm.Encrypt(nonce, buffer, cyphertext, tag);
                logger.Log($"Cypher: {string.Join(',', cyphertext)}", LoggerState.Debug);
                logger.Log($"Tag: {string.Join(',', tag)}", LoggerState.Debug);
                logger.Log($"Nonce: {string.Join(',', nonce)}", LoggerState.Debug);

                byte[] unifiedEnc = new byte[cyphertext.Length + tag.Length];
                cyphertext.CopyTo(unifiedEnc, 0);
                tag.CopyTo(unifiedEnc, cyphertext.Length);

                client.Send(unifiedEnc, unifiedEnc.Length, SocketFlags.None);
            }
            client.SendBufferSize = clientSendBuffer;
        }