コード例 #1
0
ファイル: Branca.cs プロジェクト: xlxl85/branca-dotnet
        public string Decode(string token, int?ttl = null)
        {
            var tokenBytes = token.FromBase62();

            var headerBytes = new byte[HeaderBytes];

            Buffer.BlockCopy(tokenBytes, 0, headerBytes, 0, HeaderBytes);

            var nonceBytes = new byte[NonceBytes];

            Buffer.BlockCopy(headerBytes, VersionByte + TimestampBytes, nonceBytes, 0, NonceBytes);

            var cipherBytes = new byte[tokenBytes.Length - HeaderBytes];

            Buffer.BlockCopy(tokenBytes, headerBytes.Length, cipherBytes, 0, cipherBytes.Length);

            var keyBytes = new byte[Snuffle.KEY_SIZE_IN_BYTES];

            Buffer.BlockCopy(_key.ToCharArray(), 0, keyBytes, 0, _key.ToCharArray().Length);

            var aead       = new ChaCha20Poly1305(keyBytes);
            var cipherText = aead.Decrypt(cipherBytes, null, nonceBytes);

            return(cipherText.GetString());
        }
コード例 #2
0
        private void TestExceptions()
        {
            ChaCha20Poly1305 c = new ChaCha20Poly1305();

            try
            {
                c = new ChaCha20Poly1305(new SipHash());

                Fail("incorrect mac size not picked up");
            }
            catch (ArgumentException e)
            {
                // expected
            }

            try
            {
                c.Init(false, new KeyParameter(new byte[32]));

                Fail("illegal argument not picked up");
            }
            catch (ArgumentException e)
            {
                // expected
            }

            AeadTestUtilities.TestTampering(this, c, new AeadParameters(new KeyParameter(new byte[32]), 128, new byte[12]));

            byte[] P   = Strings.ToByteArray("Hello world!");
            byte[] buf = new byte[100];

            c = new ChaCha20Poly1305();
            AeadParameters aeadParameters = new AeadParameters(new KeyParameter(new byte[32]), 128, new byte[12]);

            c.Init(true, aeadParameters);

            c.ProcessBytes(P, 0, P.Length, buf, 0);

            c.DoFinal(buf, 0);

            try
            {
                c.DoFinal(buf, 0);
                Fail("no exception on reuse");
            }
            catch (InvalidOperationException e)
            {
                IsTrue("wrong message", e.Message.Equals("ChaCha20Poly1305 cannot be reused for encryption"));
            }

            try
            {
                c.Init(true, aeadParameters);
                Fail("no exception on reuse");
            }
            catch (ArgumentException e)
            {
                IsTrue("wrong message", e.Message.Equals("cannot reuse nonce for ChaCha20Poly1305 encryption"));
            }
        }
コード例 #3
0
        public void RandomNonceTest()
        {
            var rnd = new Random();
            var key = new byte[Snuffle.KEY_SIZE_IN_BYTES];

            rnd.NextBytes(key);

            var aead = new ChaCha20Poly1305(key);

            var message     = new byte[0];
            var aad         = new byte[0];
            var ciphertexts = new HashSet <string>();
            var samples     = 1 << 17;

            for (var i = 0; i < samples; i++)
            {
                var ct    = aead.Encrypt(message, aad);
                var ctHex = CryptoBytes.ToHexStringLower(ct);

                Assert.IsFalse(ciphertexts.Contains(ctHex));
                ciphertexts.Add(ctHex);
            }

            Assert.AreEqual(samples, ciphertexts.Count);
        }
コード例 #4
0
        private void RunTestCase(
            string testName,
            byte[]  K,
            byte[]  N,
            byte[]  A,
            byte[]  SA,
            byte[]  P,
            byte[]  C,
            byte[]  T)
        {
            AeadParameters   parameters = new AeadParameters(new KeyParameter(K), T.Length * 8, N, A);
            ChaCha20Poly1305 encCipher  = InitCipher(true, parameters);
            ChaCha20Poly1305 decCipher  = InitCipher(false, parameters);

            CheckTestCase(encCipher, decCipher, testName, SA, P, C, T);
            encCipher = InitCipher(true, parameters);
            CheckTestCase(encCipher, decCipher, testName + " (reused)", SA, P, C, T);

            // Key reuse
            AeadParameters keyReuseParams = AeadTestUtilities.ReuseKey(parameters);

            try
            {
                encCipher.Init(true, keyReuseParams);
                Fail("no exception");
            }
            catch (ArgumentException e)
            {
                IsTrue("wrong message", "cannot reuse nonce for ChaCha20Poly1305 encryption".Equals(e.Message));
            }
        }
コード例 #5
0
        public DNSCrypt(IOptionsMonitor <DNSCryptOptions> DNSCryptOptions)
        {
            Options = DNSCryptOptions;

            Random = new Random();

            Client = new UdpClient
            {
                Client =
                {
                    SendTimeout    = Options.CurrentValue.Timeout,
                    ReceiveTimeout = Options.CurrentValue.Timeout
                }
            };

            Stamp = (DNSCryptStamp)Options.CurrentValue.Stamp.Value;

            IPEndPoint = IPEndPoint.Parse(Stamp.Address);

            var ClientCurve25519 = new Curve25519();

            ClientPublicKey = ClientCurve25519.GetPublicKey();

            ClientPrivateKey = ClientCurve25519.GetPrivateKey();

            ChaCha20Poly1305 = new ChaCha20Poly1305();

            IsInitialized = false;
        }
コード例 #6
0
        public void DecryptWhenNonceIsEmptyFails()
        {
            // Arrange, Act & Assert
            var aead = new ChaCha20Poly1305(new byte[Snuffle.KEY_SIZE_IN_BYTES]);

            Assert.Throws <CryptographicException>(() => aead.Decrypt(new byte[50], new byte[0], new byte[0]), EXCEPTION_MESSAGE_NONCE_LENGTH);
        }
コード例 #7
0
        public void EncryptDecryptLongMessagesWithNonceTest()
        {
            var rnd = new Random();

            var dataSize = 16;

            while (dataSize <= (1 << 24))
            {
                var plaintext = new byte[dataSize];
                rnd.NextBytes(plaintext);

                var aad = new byte[dataSize / 3];
                rnd.NextBytes(aad);

                var nonce = new byte[12];
                rnd.NextBytes(nonce);

                var key = new byte[Snuffle.KEY_SIZE_IN_BYTES];
                rnd.NextBytes(key);

                var aead       = new ChaCha20Poly1305(key);
                var ciphertext = aead.Encrypt(plaintext, aad, nonce);
                var decrypted  = aead.Decrypt(ciphertext, aad, nonce);

                //Assert.AreEqual(plaintext, decrypted);
                Assert.IsTrue(CryptoBytes.ConstantTimeEquals(plaintext, decrypted));
                dataSize += 5 * dataSize / 11;
            }
        }
コード例 #8
0
        public void Decrypt(Tests.Vectors.Rfc8439TestVector test)
        {
            var aead      = new ChaCha20Poly1305(test.Key);
            var plaintext = new byte[test.CipherText.Length];

            aead.Decrypt(test.Nonce, test.CipherText, test.Tag, plaintext, test.Aad);
        }
コード例 #9
0
        public void DecryptWhenNonceLengthIsInvalidFails()
        {
            // Arrange, Act & Assert
            var aead = new ChaCha20Poly1305(new byte[Snuffle.KEY_SIZE_IN_BYTES]);

            Assert.Throws <CryptographicException>(() => aead.Decrypt(new byte[50], new byte[0], new byte[12 + TestHelpers.ReturnRandomPositiveNegative()]), EXCEPTION_MESSAGE_NONCE_LENGTH);
        }
コード例 #10
0
        private ChaCha20Poly1305 InitCipher(bool forEncryption, AeadParameters parameters)
        {
            ChaCha20Poly1305 c = new ChaCha20Poly1305();

            c.Init(forEncryption, parameters);
            return(c);
        }
コード例 #11
0
        public void EncryptDecryptWithNonceTest()
        {
            var rnd = new Random();
            var key = new byte[Snuffle.KEY_SIZE_IN_BYTES];

            rnd.NextBytes(key);

            var aead = new ChaCha20Poly1305(key);

            for (var i = 0; i < 100; i++)
            {
                var message = new byte[100];
                rnd.NextBytes(message);

                var aad = new byte[16];
                rnd.NextBytes(aad);

                var nonce = new byte[12];
                rnd.NextBytes(nonce);

                var ciphertext = aead.Encrypt(message, aad, nonce);
                var decrypted  = aead.Decrypt(ciphertext, aad, nonce);

                //Assert.AreEqual(message, decrypted);
                Assert.IsTrue(CryptoBytes.ConstantTimeEquals(message, decrypted));
            }
        }
コード例 #12
0
        private byte[] GenerateCipherStream(byte[] key, uint fillerSize)
        {
            byte[] zeroData = new byte[fillerSize];
            var    cipher   = ChaCha20Poly1305.ChaCha20Encrypt(zeroData, key, Nonce);

            return(cipher);
        }
コード例 #13
0
        /// <summary>Method which encrypts a string using ChaCha20.</summary>
        private void Encrypt()
        {
            var enc = new ChaCha20Poly1305(Encoding.ASCII.GetBytes(Key));

            EncryptedPassword    = enc.Encrypt(Encoding.ASCII.GetBytes(HashedPassword));
            EncryptedPasswordb64 = Convert.ToBase64String(EncryptedPassword);
        }
コード例 #14
0
        private byte[] EncryptOrDecrypt(bool forEncryption, byte[] data, byte[] key, byte[] nonce)
        {
            if (ExpectedKeySize != key.Length)
            {
                throw new CryptoException("Invalid key size");
            }
            if (ExpectedNonceSize != nonce.Length)
            {
                throw new CryptoException("Invalid nonce size");
            }

            // We do the X-part of XChaCha20 and then use the ChaCha20 from bouncy castle
            byte[] subkey = new byte[KeySizeBytes];
            ChaCha20Base.HChaCha20(subkey, key, nonce);
            byte[] chaChaNonce = CreateChaChaNonce(nonce);

            ICipherParameters aeadParams = new AeadParameters(
                new KeyParameter(subkey), MacSizeBytes * 8, chaChaNonce, null);
            IAeadCipher chaCha20Poly1305 = new ChaCha20Poly1305();

            chaCha20Poly1305.Init(forEncryption, aeadParams);

            byte[] result = new byte[chaCha20Poly1305.GetOutputSize(data.Length)];
            int    len    = chaCha20Poly1305.ProcessBytes(data, 0, data.Length, result, 0);

            chaCha20Poly1305.DoFinal(result, len);
            return(result);
        }
コード例 #15
0
        public static void Properties()
        {
            var a = new ChaCha20Poly1305();

            Assert.Equal(32, a.KeySize);
            Assert.Equal(12, a.NonceSize);
            Assert.Equal(16, a.TagSize);
        }
コード例 #16
0
        public void DecryptWithNonceWhenCiphertextIsTooShortFails()
        {
            // Arrange & Act
            var aead = new ChaCha20Poly1305(new byte[Snuffle.KEY_SIZE_IN_BYTES]);

            // Assert
            Assert.Throws <CryptographicException>(() => aead.Decrypt(new byte[27], new byte[1], new byte[1]));
        }
コード例 #17
0
        //Can we change the ChaCha20Poly1305 input to some kind of ICrypto interface or action with 'Encrypt' and 'Decrypt'?
        private void Pack(IBufferWriter <byte> output, CryptoDtoHeaderDto header, ChaCha20Poly1305 crypto, ReadOnlySpan <byte> dtoNameBuffer, ReadOnlySpan <byte> dtoBuffer)
        {
            lock (bufferLock)
            {
                headerBuffer.Clear();
                MessagePackSerializer.Serialize(headerBuffer, header);
                ReadOnlySpan <byte> headerBytes = headerBuffer.WrittenSpan;

                ushort headerLength = (ushort)headerBytes.Length;
                BinaryPrimitives.WriteUInt16LittleEndian(headerLengthBytes, headerLength);
                ushort dtoNameLength = (ushort)dtoNameBuffer.Length;
                BinaryPrimitives.WriteUInt16LittleEndian(dtoNameLengthBytes, dtoNameLength);
                ushort dtoLength = (ushort)dtoBuffer.Length;
                BinaryPrimitives.WriteUInt16LittleEndian(dtoLengthBytes, dtoLength);

                switch (header.Mode)
                {
                case CryptoDtoMode.ChaCha20Poly1305:
                {
                    int adLength = 2 + headerLength;
                    int aeLength = 2 + dtoNameLength + 2 + dtoLength;

                    // Copy data into associated data buffer
                    adBuffer.Clear();
                    adBuffer.Write(headerLengthBytes);
                    adBuffer.Write(headerBytes);

                    // Copy data into authenticated encryption buffer
                    aeBuffer.Clear();
                    aeBuffer.Write(dtoNameLengthBytes);
                    aeBuffer.Write(dtoNameBuffer);
                    aeBuffer.Write(dtoLengthBytes);
                    aeBuffer.Write(dtoBuffer);

                    Span <byte> nonceSpan = new Span <byte>(nonceBytes);
                    BinaryPrimitives.WriteUInt64LittleEndian(nonceSpan.Slice(4), header.Sequence);

                    var adSpan         = adBuffer.WrittenSpan;
                    var aeSpan         = aeBuffer.WrittenSpan;
                    var cipherTextSpan = cipherText.Span.Slice(0, aeLength);
                    cipherTextSpan.Clear();
                    Span <byte> tagSpan = tagBuffer;
                    tagSpan.Clear();
                    crypto.Encrypt(nonceSpan, aeSpan, cipherTextSpan, tagSpan, adSpan);

                    output.Write(adSpan);
                    output.Write(cipherTextSpan);
                    output.Write(tagSpan);
                    break;
                }

                default:
                    throw new CryptographicException("Mode not recognised");
                }
            }
        }
コード例 #18
0
        public void ModifiedCiphertextFails()
        {
            var rnd = new Random();
            var key = new byte[Snuffle.KEY_SIZE_IN_BYTES];

            rnd.NextBytes(key);

            var aad = new byte[16];

            rnd.NextBytes(aad);

            var message = new byte[32];

            rnd.NextBytes(message);

            var aead       = new ChaCha20Poly1305(key);
            var ciphertext = aead.Encrypt(message, aad);

            // Flipping bits
            for (var b = 0; b < ciphertext.Length; b++)
            {
                for (var bit = 0; bit < 8; bit++)
                {
                    var modified = new byte[ciphertext.Length];
                    Array.Copy(ciphertext, modified, ciphertext.Length);

                    modified[b] ^= (byte)(1 << bit);

                    Assert.Throws <CryptographicException>(() => aead.Decrypt(modified, aad), SnufflePoly1305.AEAD_EXCEPTION_INVALID_TAG);
                }
            }

            // Truncate the message
            for (var length = 0; length < ciphertext.Length; length++)
            {
                var modified = new byte[length];
                Array.Copy(ciphertext, modified, length);

                Assert.Throws <CryptographicException>(() => aead.Decrypt(modified, aad), SnufflePoly1305.AEAD_EXCEPTION_INVALID_TAG);
            }

            // Modify AAD
            for (var b = 0; b < aad.Length; b++)
            {
                for (var bit = 0; bit < 8; bit++)
                {
                    var modified = new byte[aad.Length];
                    Array.Copy(aad, modified, aad.Length);

                    modified[b] ^= (byte)(1 << bit);

                    Assert.Throws <CryptographicException>(() => aead.Decrypt(modified, aad), SnufflePoly1305.AEAD_EXCEPTION_INVALID_TAG);
                }
            }
        }
コード例 #19
0
        public void EncryptWithADTestWithoutPlainTextMacTest()
        {
            String key                  = "e68f69b7f096d7917245f5e5cf8ae1595febe4d4644333c99f9c4a1282031c9f";
            String additionalData       = "9e0e7de8bb75554f21db034633de04be41a2b8a18da7a319a03c803bf02b396c";
            String expectedCipherResult = "0df6086551151f58b8afe6c195782c6a";

            Nonce nonce = new Nonce();

            (byte[] actualCipherText, byte[] mac) = ChaCha20Poly1305.EncryptWithAdditionalData(key.HexToByteArray(), nonce.GetBytes(), additionalData.HexToByteArray(), new byte[0]);
            Assert.Equal(new byte[0], actualCipherText);
            Assert.Equal(expectedCipherResult, mac.ToHex());
        }
コード例 #20
0
        private static byte[] Pack(string channelTag, CryptoDtoMode mode, ReadOnlySpan <byte> transmitKey, ulong sequenceToBeSent, byte[] dtoNameBuffer, byte[] dtoBuffer)
        {
            CryptoDtoHeaderDto header = new CryptoDtoHeaderDto
            {
                ChannelTag = channelTag,
                Sequence   = sequenceToBeSent,
                Mode       = mode
            };

            var    headerBuffer  = MessagePackSerializer.Serialize(header);
            ushort headerLength  = (ushort)headerBuffer.Length;
            ushort dtoNameLength = (ushort)dtoNameBuffer.Length;
            ushort dtoLength     = (ushort)dtoBuffer.Length;

            switch (header.Mode)
            {
            case CryptoDtoMode.ChaCha20Poly1305:
            {
                int aePayloadLength = 2 + dtoNameLength + 2 + dtoLength;
                var aePayloadBuffer = new byte[aePayloadLength];

                Array.Copy(BitConverter.GetBytes(dtoNameLength), 0, aePayloadBuffer, 0, 2);
                Array.Copy(dtoNameBuffer, 0, aePayloadBuffer, 2, dtoNameLength);

                Array.Copy(BitConverter.GetBytes(dtoLength), 0, aePayloadBuffer, 2 + dtoNameLength, 2);
                Array.Copy(dtoBuffer, 0, aePayloadBuffer, 2 + dtoNameLength + 2, dtoLength);

                int adPayloadLength = 2 + headerLength;
                var adPayloadBuffer = new byte[adPayloadLength];

                Array.Copy(BitConverter.GetBytes(headerLength), 0, adPayloadBuffer, 0, 2);
                Array.Copy(headerBuffer, 0, adPayloadBuffer, 2, headerLength);

                Span <byte> nonceBuffer = stackalloc byte[Aead.NonceSize];
                BinaryPrimitives.WriteUInt64LittleEndian(nonceBuffer.Slice(4), header.Sequence);

                var    aead              = new ChaCha20Poly1305(transmitKey.ToArray());
                byte[] aeadPayload       = aead.Encrypt(aePayloadBuffer, adPayloadBuffer, nonceBuffer);
                int    aeadPayloadLength = aeadPayload.Length;

                byte[] packetBuffer = new byte[2 + headerLength + aeadPayloadLength];

                Array.Copy(BitConverter.GetBytes(headerLength), 0, packetBuffer, 0, 2);
                Array.Copy(headerBuffer, 0, packetBuffer, 2, headerLength);
                Array.Copy(aeadPayload, 0, packetBuffer, 2 + headerLength, aeadPayloadLength);
                return(packetBuffer);
            }

            default:
                throw new CryptographicException("Mode not recognised");
            }
        }
コード例 #21
0
        private static byte[] XChaCha20Poly1305(bool isEncryption, byte[] key, byte[] nonce, byte[] message, byte[] aad = null)
        {
            if (key.Length != 32)
            {
                throw new ArgumentException("Key must be 32 bytes", nameof(key));
            }
            if (nonce.Length != 24)
            {
                throw new ArgumentException("Nonce must be 24 bytes", nameof(nonce));
            }

            // subkey (hchacha20(key, nonce[0:15]))
            var subkey = HChaCha20.CreateSubkey(key, nonce); // TODO: parse nonce bytes to pass through here instead

            // nonce (chacha20_nonce = "\x00\x00\x00\x00" + nonce[16:23])
            var chaChaNonce = new byte[12];

            Array.Copy(new byte[] { 0, 0, 0, 0 }, chaChaNonce, 4);
            Array.Copy(nonce, 16, chaChaNonce, 4, 8);

            // chacha20_encrypt(subkey, chacha20_nonce, plaintext, blk_ctr)
            var outputLength = message.Length;

            if (isEncryption)
            {
                outputLength += 16;
            }
            else
            {
                outputLength -= 16;
            }

            var output      = new byte[outputLength];
            var keyMaterial = new KeyParameter(subkey);
            var parameters  = new ParametersWithIV(keyMaterial, chaChaNonce);

            var chaCha20Poly1305 = new ChaCha20Poly1305();

            chaCha20Poly1305.Init(isEncryption, parameters);

            // if aditional data present
            if (aad != null)
            {
                chaCha20Poly1305.ProcessAadBytes(aad, 0, aad.Length);
            }

            var len = chaCha20Poly1305.ProcessBytes(message, 0, message.Length, output, 0);

            chaCha20Poly1305.DoFinal(output, len);

            return(output);
        }
コード例 #22
0
        public static void EncryptDecryptNullTag()
        {
            byte[] key        = "fde37f01fe9ca260f432e0ed98b3e0bb23895ca1ca1ce2cfcaaca2ccc98889d7".HexToByteArray();
            byte[] nonce      = new byte[NonceSizeInBytes];
            byte[] plaintext  = new byte[0];
            byte[] ciphertext = new byte[0];

            using (var chaChaPoly = new ChaCha20Poly1305(key))
            {
                Assert.Throws <ArgumentNullException>(() => chaChaPoly.Encrypt(nonce, plaintext, ciphertext, (byte[])null));
                Assert.Throws <ArgumentNullException>(() => chaChaPoly.Decrypt(nonce, ciphertext, (byte[])null, plaintext));
            }
        }
コード例 #23
0
            internal Deserializer(CryptoDtoChannelStore channelStore, ReadOnlySpan <byte> bytes, bool ignoreSequence)
            {
                sequenceValid = false;
                headerLength  = Unsafe.ReadUnaligned <ushort>(ref MemoryMarshal.GetReference(bytes));           //.NET Standard 2.0 doesn't have BitConverter.ToUInt16(Span<T>)
                if (bytes.Length < (2 + headerLength))
                {
                    throw new CryptographicException("Not enough bytes to process packet.");
                }

                ReadOnlySpan <byte> headerDataBuffer = bytes.Slice(2, headerLength);

                header = MessagePackSerializer.Deserialize <CryptoDtoHeaderDto>(headerDataBuffer.ToArray());
                ReadOnlySpan <byte> receiveKey = channelStore.GetReceiveKey(header.ChannelTag, header.Mode);                 //This will throw exception if channel tag isn't in the store

                switch (header.Mode)
                {
                case CryptoDtoMode.ChaCha20Poly1305:
                {
                    int aeLength = bytes.Length - (2 + headerLength);
                    ReadOnlySpan <byte> aePayloadBuffer = bytes.Slice(2 + headerLength, aeLength);

                    ReadOnlySpan <byte> adBuffer = bytes.Slice(0, 2 + headerLength);

                    Span <byte> nonceBuffer = stackalloc byte[Aead.NonceSize];
                    BinaryPrimitives.WriteUInt64LittleEndian(nonceBuffer.Slice(4), header.Sequence);

                    var aead = new ChaCha20Poly1305(receiveKey.ToArray());
                    ReadOnlySpan <byte> decryptedPayload = aead.Decrypt(aePayloadBuffer.ToArray(), adBuffer.ToArray(), nonceBuffer);

                    if (ignoreSequence)
                    {
                        sequenceValid = channelStore.IsReceivedSequenceAllowed(header.ChannelTag, header.Sequence);
                    }
                    else
                    {
                        channelStore.CheckReceivedSequence(header.ChannelTag, header.Sequence);             //The packet has passed MAC, so now check if it's being duplicated or replayed
                        sequenceValid = true;
                    }

                    dtoNameLength = Unsafe.ReadUnaligned <ushort>(ref MemoryMarshal.GetReference(decryptedPayload));           //.NET Standard 2.0 doesn't have BitConverter.ToUInt16(Span<T>)
                    dtoNameBuffer = decryptedPayload.Slice(2, dtoNameLength);

                    dataLength = Unsafe.ReadUnaligned <ushort>(ref MemoryMarshal.GetReference(decryptedPayload.Slice(2 + dtoNameLength, 2)));           //.NET Standard 2.0 doesn't have BitConverter.ToUInt16(Span<T>)
                    dataBuffer = decryptedPayload.Slice(2 + dtoNameLength + 2, dataLength);
                    break;
                }

                default:
                    throw new CryptographicException("Mode not recognised");
                }
            }
コード例 #24
0
        public static void PlaintextAndCiphertextSizeDiffer(int ptLen, int ctLen)
        {
            byte[] key        = new byte[KeySizeInBytes];
            byte[] nonce      = new byte[NonceSizeInBytes];
            byte[] plaintext  = new byte[ptLen];
            byte[] ciphertext = new byte[ctLen];
            byte[] tag        = new byte[TagSizeInBytes];

            using (var chaChaPoly = new ChaCha20Poly1305(key))
            {
                Assert.Throws <ArgumentException>(() => chaChaPoly.Encrypt(nonce, plaintext, ciphertext, tag));
                Assert.Throws <ArgumentException>(() => chaChaPoly.Decrypt(nonce, ciphertext, tag, plaintext));
            }
        }
コード例 #25
0
        public byte[] ReadMessageData(byte[] messageData)
        {
            (byte[] decryptedMessage, _) = ChaCha20Poly1305.DecryptWithAdditionalData(_transportState.ReceiveDecryptionKey,
                                                                                      _transportState.ReceiveNonce.GetBytes(), new byte[0], messageData);

            _transportState.ReceiveNonce.Increment();

            if (_transportState.ReceiveNonce.Value == 1000)
            {
                _transportState.RotateReceiveKey();
            }

            return(decryptedMessage.SubArray(0, messageData.Length - 16));
        }
コード例 #26
0
        public void EncryptWithADTestWithPlainText()
        {
            String key                  = "908b166535c01a935cf1e130a5fe895ab4e6f3ef8855d87e9b7581c4ab663ddc";
            String additionalData       = "90578e247e98674e661013da3c5c1ca6a8c8f48c90b485c0dfa1494e23d56d72";
            String plaintext            = "034f355bdcb7cc0af728ef3cceb9615d90684bb5b2ca5f859ab0f0b704075871aa";
            String expectedCipherResult = "b9e3a702e93e3a9948c2ed6e5fd7590a6e1c3a0344cfc9d5b57357049aa22355361aa02e55a8fc28fef5bd6d71ad0c3822";

            Nonce nonce = new Nonce();

            nonce.Increment();

            (byte[] actualCipherText, byte[] mac) = ChaCha20Poly1305.EncryptWithAdditionalData(key.HexToByteArray(), nonce.GetBytes(), additionalData.HexToByteArray(), plaintext.HexToByteArray());

            Assert.Equal(expectedCipherResult, actualCipherText.ToHex() + mac.ToHex());
        }
コード例 #27
0
        public static void Rfc8439Tests(AEADTest testCase)
        {
            using (var chaChaPoly = new ChaCha20Poly1305(testCase.Key))
            {
                byte[] ciphertext = new byte[testCase.Plaintext.Length];
                byte[] tag        = new byte[testCase.Tag.Length];
                chaChaPoly.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];
                chaChaPoly.Decrypt(testCase.Nonce, ciphertext, tag, plaintext, testCase.AssociatedData);
                Assert.Equal(testCase.Plaintext, plaintext);
            }
        }
コード例 #28
0
        /// <summary>Method which verifies that a supplied plain-text password matches the encrypted password.</summary>
        public bool Verify(string plaintext)
        {
            if (EncryptedPasswordb64 == null)
            {
                throw new Exception("You must have an encrypted password to verify against");
            }

            // Unpack the Encrypted Password
            var base10          = Convert.FromBase64String(EncryptedPasswordb64);
            var dec             = new ChaCha20Poly1305(Encoding.ASCII.GetBytes(Key));
            var decryptedBytes  = dec.Decrypt(base10);
            var decryptedString = Encoding.ASCII.GetString(decryptedBytes);

            return(PasswordHash.ArgonHashStringVerify(decryptedString, plaintext));
        }
コード例 #29
0
        public static void InvalidTagSize(int tagSize)
        {
            int dataLength = 30;

            byte[] plaintext  = Enumerable.Range(1, dataLength).Select((x) => (byte)x).ToArray();
            byte[] ciphertext = new byte[dataLength];
            byte[] key        = RandomNumberGenerator.GetBytes(KeySizeInBytes);
            byte[] nonce      = RandomNumberGenerator.GetBytes(NonceSizeInBytes);
            byte[] tag        = new byte[tagSize];

            using (var chaChaPoly = new ChaCha20Poly1305(key))
            {
                Assert.Throws <ArgumentException>("tag", () => chaChaPoly.Encrypt(nonce, plaintext, ciphertext, tag));
            }
        }
コード例 #30
0
        public void Setup()
        {
            key = new byte[Snuffle.KEY_SIZE_IN_BYTES];
            rnd.NextBytes(key);

            message = new byte[Size];
            rnd.NextBytes(message);

            aad = new byte[16];
            rnd.NextBytes(aad);

            nonce = new byte[12];
            rnd.NextBytes(nonce);

            aead = new ChaCha20Poly1305(key);
        }