Exemple #1
0
        public void ClientEncryption4Queue()
        {
            var    kv       = new KeyVaultTester("624c0e2f-6122-4b26-a229-06431f82e6b3", "C35CBFF9FA6C51E51E1DE97B6D1E246F27661301", "https://kvsignalrdeva.vault.azure.net");
            var    name     = "AzSignalR-Storage-ClientEncryptionKey";
            var    rsaValue = kv.GetSecretAsync(name).Result;
            string kid      = "signalrkeyid";

            StorageRunnerContext.RunOnQueue(storage,
                                            "jwtestqueuea" + Guid.NewGuid().ToString().Substring(0, 8),
                                            (cloudQueue) =>
            {
                var csp1 = new RSACryptoServiceProvider();
                csp1.FromXmlString(rsaValue);
                var rsa1 = new RsaKey(kid, csp1);
                QueueEncryptionPolicy policy = new QueueEncryptionPolicy(rsa1, null);
                QueueRequestOptions options  = new QueueRequestOptions()
                {
                    EncryptionPolicy = policy
                };
                cloudQueue.AddMessage(new CloudQueueMessage("messageContentABC"), null, null, options, null);

                // Retrieve message
                var csp2 = new RSACryptoServiceProvider();
                csp2.FromXmlString(rsaValue);
                var rsa2 = new RsaKey(kid, csp2);
                QueueEncryptionPolicy policy2 = new QueueEncryptionPolicy(rsa2, null);
                QueueRequestOptions options2  = new QueueRequestOptions()
                {
                    EncryptionPolicy = policy2
                };
                CloudQueueMessage retrMessage = cloudQueue.GetMessage(null, options2, null);
                Console.WriteLine(retrMessage.AsString);
            });
        }
Exemple #2
0
        public void RestoreLeadingZeros_doesnt_change_valid_parameters()
        {
            var rsa = new RSAParameters
            {
                Exponent = RsaKeyData.Exponent.Decode64Loose(),
                Modulus  = RsaKeyData.Modulus.Decode64Loose(),
                P        = RsaKeyData.P.Decode64Loose(),
                Q        = RsaKeyData.Q.Decode64Loose(),
                DP       = RsaKeyData.DP.Decode64Loose(),
                DQ       = RsaKeyData.DQ.Decode64Loose(),
                InverseQ = RsaKeyData.InverseQ.Decode64Loose(),
                D        = RsaKeyData.D.Decode64Loose(),
            };

            var padded = RsaKey.RestoreLeadingZeros(rsa);

            Assert.Equal(rsa.Exponent, padded.Exponent);
            Assert.Equal(rsa.Modulus, padded.Modulus);
            Assert.Equal(rsa.P, padded.P);
            Assert.Equal(rsa.Q, padded.Q);
            Assert.Equal(rsa.DP, padded.DP);
            Assert.Equal(rsa.DQ, padded.DQ);
            Assert.Equal(rsa.InverseQ, padded.InverseQ);
            Assert.Equal(rsa.D, padded.D);
        }
        public void Setup()
        {
            privateKey = new RsaKey(null, AsymmetricKeyType.Encrypted, 4096);
            publicKey  = new RsaKey(null, AsymmetricKeyType.Public, 2048);

            keyPair = new AsymmetricKeyPair(privateKey, publicKey);
        }
Exemple #4
0
        public void RestoreLeadingZeros_pads_to_correct_length()
        {
            var rsa = new RSAParameters
            {
                Exponent = new byte[3],
                Modulus  = new byte[2048 / 8 - 1],
                P        = new byte[13],
                Q        = new byte[17],
                DP       = new byte[23],
                DQ       = new byte[37],
                InverseQ = new byte[53],
                D        = new byte[133],
            };

            var padded = RsaKey.RestoreLeadingZeros(rsa);

            Assert.Equal(3, padded.Exponent.Length);
            Assert.Equal(2048 / 8, padded.Modulus.Length);
            Assert.Equal(1024 / 8, padded.P.Length);
            Assert.Equal(1024 / 8, padded.Q.Length);
            Assert.Equal(1024 / 8, padded.DP.Length);
            Assert.Equal(1024 / 8, padded.DQ.Length);
            Assert.Equal(1024 / 8, padded.InverseQ.Length);
            Assert.Equal(2048 / 8, padded.D.Length);
        }
        public void Given_PublicKeyWithDetailsFromPrivateKey_When_GetKeyType_Then_ExceptionThrownOrPublicEnumIsRetunedDependingOnFlag(
            [Values(true, false)] bool throwExceptionWhenPublicKeyHasTooMuchInfo)
        {
            // Arrange
            var rsaKey = new RsaKey(new RSAParameters()
            {
                Exponent = new byte[1],
                Modulus  = new byte[1],
                D        = new byte[1]
            }, true);

            // Act
            var    res = KeyTypeEnum.Private;
            Action act = () => res = rsaKey.GetKeyType(throwExceptionWhenPublicKeyHasTooMuchInfo);

            // Assert
            if (throwExceptionWhenPublicKeyHasTooMuchInfo)
            {
                act.ShouldThrow <EnvCryptException>()
                .And.Message.Should()
                .Contain("has information from the private key");
            }
            else
            {
                act.ShouldNotThrow <EnvCryptException>();
                res.Should().Be(KeyTypeEnum.Public);
            }
        }
Exemple #6
0
        public void RsaCipherConstructorTest()
        {
            RsaKey    key    = null; // TODO: Initialize to an appropriate value
            RsaCipher target = new RsaCipher(key);

            Assert.Inconclusive("TODO: Implement code to verify target");
        }
Exemple #7
0
        private byte[] CalculateRSA(byte[] input, RsaKey Key, bool isSigning = true)
        {
            List <byte> result = new List <byte>(input.Length);

            int readingSize = isSigning ? Key.ReadingSize : Key.PackingSize;
            int packingSize = isSigning ? Key.PackingSize : Key.ReadingSize;

            for (int i = 0; i < input.Length; i += readingSize)
            {
                int countOfBytes = Math.Min(readingSize, input.Length - i); // calculate count of bytes in block

                byte[] block = new byte[countOfBytes + 1];

                Buffer.BlockCopy(input, i, block, 0, countOfBytes);

                byte[] tempResult = ModifyMessage(block, Key, isSigning).ToByteArray();

                byte[] packingUnit = new byte[packingSize];

                Buffer.BlockCopy(tempResult, 0, packingUnit, 0, Math.Min(packingUnit.Length, tempResult.Length)); //copy to packing block from result of ciphering

                result.AddRange(packingUnit);
            }

            return(result.ToArray());
        }
        public int GetMaxBytesThatCanBeEncrypted(RsaKey key)
        {
            Contract.Requires <ArgumentNullException>(key != null, "key");
            Contract.Ensures(Contract.Result <int>() > 0);

            return(default(int));
        }
Exemple #9
0
 public void GenerateWithEmbeddedDataNull_Should_Succeed()
 {
     // Arrange
     // Act
     // Assert
     RsaKey.Generate(embeddedData: null);
 }
Exemple #10
0
 public void GenerateWithoutSignature_Should_Succeed()
 {
     // Arrange
     // Act
     // Assert
     RsaKey.Generate().Should().NotBeNull();
 }
Exemple #11
0
        public void SetUp()
        {
            _rsaCryptoUtil = new RsaPkcs8CryptoUtil();
            _bytesUtil     = new BytesUtil();

            //_key = _rsaCryptoUtil.GenerateKeys();
            _key = new RsaKey
            {
                Private = @"-----BEGIN PRIVATE KEY-----
MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAPFSWsy4T/cW5aXD
aAHHIEPpD5VBYQL/VgSyBTh0WUIg4SnXI8IIP8HozkijxMcagt5gXdfb2wa0KxO6
yy6Yyzt1GfzAG2ijN0gB72s8tXgmbTCw7eAHEr+SsLMdHWPPXzQgixIQrmiPwEqi
/ACwelWSjHbu8vYC63dCdIpuPBUDAgMBAAECgYBEmYqiQ4rHzMR/eKrqRnbPl0MM
xMcVGQyUzR5azAhLmhkn0baig8HMF6f8UkGv78Nf/7jtkdwTbcgJFcKIfnrW4Lyw
FF9hwGVf2bKyRqkMiZI+e307cYevKK7KU0qCw1Z4a8KCfCt0wiCcYu/Y4Epi/q2R
xy0akcGb+bBnz6B1IQJBAP3sv/3cE3EAoPKG+cmyHv+gRDxmyhjaCWvwR7CYp0jI
EWigH0G15UzcxxSOiyPk2vjX0OUa85FmABZka6YtVVsCQQDzSzywcjOIdzuy1tdH
7gFdH2zwln2VkyWrqHDkTbApIfsV3ipsgGa2bx5DCirSe29tiI9wAwXzC08qyyVZ
b8d5AkEAlObjQxtt7yMePno2OjeQg/hYa08fjek2AyzY7U7nMf/YbZEQIzlmKGeC
+qQIJdlLKwdrgR4H3KiCvp7OnZkR5wJBANoljP48994V4w6BOrkBPHHOOrUiiupx
7SYUu1zKF/lZwbQi53EwVGiiC8VauXjPOuNAvjRWUaBSdKLPUeb2pikCQQC9xErQ
DFWwCsAUf6kTPxw6Uvn5nCx3u5J3Wdx7Urfw5c3A7BBQdsu8UP6zbyhpxJCzAbAD
hhsyI5hID8mQOUY2
-----END PRIVATE KEY-----
",
                Public  = @"-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDxUlrMuE/3FuWlw2gBxyBD6Q+V
QWEC/1YEsgU4dFlCIOEp1yPCCD/B6M5Io8THGoLeYF3X29sGtCsTussumMs7dRn8
wBtoozdIAe9rPLV4Jm0wsO3gBxK/krCzHR1jz180IIsSEK5oj8BKovwAsHpVkox2
7vL2Aut3QnSKbjwVAwIDAQAB
-----END PUBLIC KEY-----
"
            };
        }
Exemple #12
0
        public byte[][] WrapNewKey(int cekSizeBits, object key, IDictionary <string, object> header)
        {
            var cek = Arrays.Random(cekSizeBits);

            if (key is CngKey)
            {
                var publicKey = (CngKey)key;

                return(new[] { cek, RsaOaep.Encrypt(cek, publicKey, CngAlgorithm.Sha256) });
            }

            if (key is RSACryptoServiceProvider)
            {
                //This is for backward compatibility only with 2.x
                //To be removed in 3.x
                var publicKey = RsaKey.New(((RSACryptoServiceProvider)key).ExportParameters(false));

                return(new[] { cek, RsaOaep.Encrypt(cek, publicKey, CngAlgorithm.Sha256) });
            }

            if (key is RSA)
            {
                var publicKey = (RSA)key;

                return(new[] { cek, publicKey.Encrypt(cek, RSAEncryptionPadding.OaepSHA256) });
            }

            throw new ArgumentException("RsaKeyManagement algorithm expects key to be of either CngKey or RSA types.");
        }
Exemple #13
0
        private protected PgpKey(KeyPacket keyPacket)
        {
            this.keyPacket         = keyPacket;
            this.keyCertifications = new List <PgpCertification>();
            this.ids = new List <PgpUser>();

            this.fingerprint = CalculateFingerprint();

            if (keyPacket.Version <= 3)
            {
                var rsaParameters = RsaKey.ReadOpenPgpPublicKey(keyPacket.KeyBytes, out var _);
                var modulus       = rsaParameters.Modulus !;

                this.keyId = (long)(((ulong)modulus[modulus.Length - 8] << 56)
                                    | ((ulong)modulus[modulus.Length - 7] << 48)
                                    | ((ulong)modulus[modulus.Length - 6] << 40)
                                    | ((ulong)modulus[modulus.Length - 5] << 32)
                                    | ((ulong)modulus[modulus.Length - 4] << 24)
                                    | ((ulong)modulus[modulus.Length - 3] << 16)
                                    | ((ulong)modulus[modulus.Length - 2] << 8)
                                    | (ulong)modulus[modulus.Length - 1]);
            }
            else
            {
                this.keyId = (long)(((ulong)fingerprint[fingerprint.Length - 8] << 56)
                                    | ((ulong)fingerprint[fingerprint.Length - 7] << 48)
                                    | ((ulong)fingerprint[fingerprint.Length - 6] << 40)
                                    | ((ulong)fingerprint[fingerprint.Length - 5] << 32)
                                    | ((ulong)fingerprint[fingerprint.Length - 4] << 24)
                                    | ((ulong)fingerprint[fingerprint.Length - 3] << 16)
                                    | ((ulong)fingerprint[fingerprint.Length - 2] << 8)
                                    | (ulong)fingerprint[fingerprint.Length - 1]);
            }
        }
        public byte[] WrapKey(byte[] cek, object key, IDictionary <string, object> header)
        {
#if NET40
            if (key is CngKey cngKey)
            {
                return(RsaOaep.Encrypt(cek, cngKey, CngAlgorithm.Sha256));
            }
            else if (key is RSACryptoServiceProvider rsaKey)
            {
                //This is for backward compatibility only with 2.x
                //To be removed in 3.x
                var publicKey = RsaKey.New(rsaKey.ExportParameters(false));

                return(RsaOaep.Encrypt(cek, publicKey, CngAlgorithm.Sha256));
            }

            throw new ArgumentException("RsaKeyManagement algorithm expects key to be of CngKey or RSACryptoServiceProvider types.");
#elif NET461 || NET472
            if (key is CngKey cngKey)
            {
                return(RsaOaep.Encrypt(cek, cngKey, CngAlgorithm.Sha256));
            }

            else if (key is RSACryptoServiceProvider rsaKey)
            {
                //This is for backward compatibility only with 2.x
                //To be removed in 3.x
                var publicKey = RsaKey.New(rsaKey.ExportParameters(false));

                return(RsaOaep.Encrypt(cek, publicKey, CngAlgorithm.Sha256));
            }
            else if (key is RSA rsa)
            {
                return(rsa.Encrypt(cek, RSAEncryptionPadding.OaepSHA256));
            }
            else if (key is Jwk jwk)
            {
                if (jwk.Kty == Jwk.KeyTypes.RSA)
                {
                    return(jwk.RsaKey().Encrypt(cek, RSAEncryptionPadding.OaepSHA256));
                }
            }

            throw new ArgumentException("RsaKeyManagement algorithm expects key to be of CngKey, RSACryptoServiceProvider, RSA types or Jwk type with kty='rsa'.");
#elif NETSTANDARD
            if (key is RSA rsa)
            {
                return(rsa.Encrypt(cek, RSAEncryptionPadding.OaepSHA256));
            }
            else if (key is Jwk jwk)
            {
                if (jwk.Kty == Jwk.KeyTypes.RSA)
                {
                    return(jwk.RsaKey().Encrypt(cek, RSAEncryptionPadding.OaepSHA256));
                }
            }

            throw new ArgumentException("RsaKeyManagement algorithm expects key to be of RSA types or Jwk type with kty='rsa'.");
#endif
        }
        public void RsaDigitalSignatureConstructorTest()
        {
            RsaKey rsaKey = null; // TODO: Initialize to an appropriate value
            RsaDigitalSignature target = new RsaDigitalSignature(rsaKey);

            Assert.Inconclusive("TODO: Implement code to verify target");
        }
Exemple #16
0
        static void Main(string[] args)
        {
            RsaKey keys = RsaCrypt.GenerateRsaKeys();

            Console.WriteLine(keys.PublicKey);
            Console.WriteLine(keys.PrivateKey);
        }
Exemple #17
0
        public void Given_ArrayOfByteArrays_When_Decrypted_Then_ByteArrayConcatenated()
        {
            // Arrange
            var listOfByteArraysToDecrypt = new List <byte[]>()
            {
                new byte[] { 1 },
                new byte[] { 2 },
                new byte[] { 3 },
            };
            var decryptedBytes = new List <byte[]>()
            {
                new byte[] { 1, 2, 3, 4 },
                new byte[] { 6, 7, 8 },
                new byte[] { 9, 10 },
            };

            var someKey            = new RsaKey(new RSAParameters(), true);
            var encryptionAlgoMock = new Mock <IEncryptionAlgo <RsaKey> >(MockBehavior.Strict);

            encryptionAlgoMock.Setup(a => a.Decrypt(listOfByteArraysToDecrypt[0], someKey))
            .Returns(decryptedBytes[0]);
            encryptionAlgoMock.Setup(a => a.Decrypt(listOfByteArraysToDecrypt[1], someKey))
            .Returns(decryptedBytes[1]);
            encryptionAlgoMock.Setup(a => a.Decrypt(listOfByteArraysToDecrypt[2], someKey))
            .Returns(decryptedBytes[2]);

            // Act
            var segEncrypt = new SegmentEncryptionAlgoStub(encryptionAlgoMock.Object);
            var result     = segEncrypt.Decrypt(listOfByteArraysToDecrypt, someKey);

            // Assert
            result.Should().BeEquivalentTo(
                decryptedBytes[0].Concat(decryptedBytes[1]).Concat(decryptedBytes[2]));
        }
Exemple #18
0
        public string AddKey(string key)
        {
            var rsaKey = new RsaKey(key);

            keys[rsaKey.Kid] = rsaKey;
            return(rsaKey.Kid);
        }
Exemple #19
0
        public byte[] Unwrap(byte[] encryptedCek, object key, int cekSizeBits, IDictionary <string, object> header)
        {
            if (key is CngKey)
            {
                var privateKey = (CngKey)key;

                return(RsaOaep.Decrypt(encryptedCek, privateKey, CngAlgorithm.Sha256));
            }

            if (key is RSACryptoServiceProvider)
            {
                //This is for backward compatibility only with 2.x
                //To be removed in 3.x
                var privateKey = RsaKey.New(((RSACryptoServiceProvider)key).ExportParameters(true));

                return(RsaOaep.Decrypt(encryptedCek, privateKey, CngAlgorithm.Sha256));
            }

            if (key is RSA)
            {
                var privateKey = (RSA)key;

                return(privateKey.Decrypt(encryptedCek, RSAEncryptionPadding.OaepSHA256));
            }

            throw new ArgumentException("RsaKeyManagement algorithm expects key to be of either CngKey or RSA types.");
        }
Exemple #20
0
        public void Given_ValidAESPublicKey_When_MapToXMLPOCO_Then_NameMappedCorrectly()
        {
            // Arrange
            var key = new RsaKey(new RSAParameters()
            {
                Exponent = new byte[1],
                Modulus  = new byte[2],
            }, true);
            const string keyName = "My Rsa Key";

            key.Name = keyName;
            var converter = new Mock <IKeyDetailsPersistConverter>(MockBehavior.Strict);

            converter.Setup(c => c.Encode(key.Key.Exponent)).Returns("exponent");
            converter.Setup(c => c.Encode(key.Key.Modulus)).Returns("modulus");

            // Act
            var aesKeyToXmlMapper = new RsaKeyToXmlMapper(converter.Object);
            var xmlPoco           = new EnvCryptKey();

            aesKeyToXmlMapper.Map(key, xmlPoco);

            // Assert
            xmlPoco.Rsa.Should().NotBeNull().And.HaveCount(1);
            xmlPoco.Name.Should().Be(keyName);
            xmlPoco.Encryption.Should().Be(EnvCryptAlgoEnum.Rsa.ToString());
            xmlPoco.Type.Should().Be(KeyTypeEnum.Public.ToString());
            xmlPoco.Rsa[0].Exponent.Should().Be("exponent");
            xmlPoco.Rsa[0].Modulus.Should().Be("modulus");
        }
Exemple #21
0
            public void CertificateRoundtrip_Should_Succeed()
            {
                // Arrange
                var signerKey = RsaKey.Generate();
                var key       = RsaKey.Generate(
                    embeddedData: new byte[] { 0xa1, 0xb2, 0xc3, 0xd4 },
                    signKeyCallback: hash => (RsaSignature)signerKey.Sign(hash));
                var certificate = (RsaCertificate)key.DeriveCertificate();

                // Act
                RsaCertificate deserialized;

                using (var memoryStream = new MemoryStream())
                {
                    Xml.Serialize(
                        certificate: certificate,
                        stream: memoryStream);
                    memoryStream.Position = 0;
                    deserialized          = Xml.DeserializeCertificate(stream: memoryStream);
                }

                // Assert
                deserialized.Hash.Equals(certificate.Hash).Should().BeTrue();
                deserialized.EmbeddedData.SequenceEqual(certificate.EmbeddedData).Should().BeTrue();
                deserialized.Signature.SignerCertificateHash.Equals(certificate.Signature.SignerCertificateHash).Should().BeTrue();
                deserialized.Signature.Signature.SequenceEqual(certificate.Signature.Signature).Should().BeTrue();
            }
        public async Task KeyVault_RsaKeyRSAOAEP()
        {
            // Arrange
            byte[] KEK = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17 };
            byte[] CEK = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF };
            byte[] EK  = { 0x96, 0x77, 0x8B, 0x25, 0xAE, 0x6C, 0xA4, 0x35, 0xF9, 0x2B, 0x5B, 0x97, 0xC0, 0x50, 0xAE, 0xD2, 0x46, 0x8A, 0xB8, 0xA1, 0x7A, 0xD8, 0x4E, 0x5D };

            RsaKey key = new RsaKey("KEK");

            var wrapped = await key.WrapKeyAsync(CEK, RsaOaep.AlgorithmName).ConfigureAwait(false);

            var unwrapped = await key.UnwrapKeyAsync(wrapped.Item1, RsaOaep.AlgorithmName).ConfigureAwait(false);

            // Assert
            Assert.True(wrapped.Item2.Equals("RSA-OAEP"));
            Assert.True(unwrapped.SequenceEqual(CEK));

            var encrypted = await key.EncryptAsync(CEK, null, null, RsaOaep.AlgorithmName).ConfigureAwait(false);

            var decrypted = await key.DecryptAsync(encrypted.Item1, null, null, null, RsaOaep.AlgorithmName).ConfigureAwait(false);

            // Assert
            Assert.True(encrypted.Item3.Equals("RSA-OAEP"));
            Assert.True(decrypted.SequenceEqual(CEK));
        }
        public async Task KeyVault_RsaKeyRSA15()
        {
            // Arrange
            byte[] KEK = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F };
            byte[] CEK = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF };
            byte[] EK  = { 0x1F, 0xA6, 0x8B, 0x0A, 0x81, 0x12, 0xB4, 0x47, 0xAE, 0xF3, 0x4B, 0xD8, 0xFB, 0x5A, 0x7B, 0x82, 0x9D, 0x3E, 0x86, 0x23, 0x71, 0xD2, 0xCF, 0xE5 };

            RsaKey key = new RsaKey("KEK");


            var wrapped = await key.WrapKeyAsync(CEK, Rsa15.AlgorithmName).ConfigureAwait(false);

            var unwrapped = await key.UnwrapKeyAsync(wrapped.Item1, Rsa15.AlgorithmName).ConfigureAwait(false);

            // Assert
            Assert.True(wrapped.Item2.Equals("RSA_15"));
            Assert.True(unwrapped.SequenceEqual(CEK));

            var encrypted = await key.EncryptAsync(CEK, null, null, Rsa15.AlgorithmName).ConfigureAwait(false);

            var decrypted = await key.DecryptAsync(encrypted.Item1, null, null, null, Rsa15.AlgorithmName).ConfigureAwait(false);

            // Assert
            Assert.True(encrypted.Item3.Equals("RSA_15"));
            Assert.True(decrypted.SequenceEqual(CEK));
        }
Exemple #24
0
        public void CheckSignatureOfRegistrationToken()
        {
            var rsa   = new RsaKey();
            var ecdsa = new Key().GetBitcoinSecret(Network.ImpleumMain);

            var token = new RegistrationToken(1,
                                              "175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W",
                                              IPAddress.Parse("172.16.1.10"),
                                              IPAddress.Parse("2001:0db8:85a3:0000:1234:8a2e:0370:7334"),
                                              "5678901234ABCDEF",
                                              "",
                                              16174,
                                              ecdsa.PubKey);

            // Only the 'header' portion of the registration token gets signed, minus the length bytes
            var message = token.GetHeaderBytes();

            var cryptoUtils = new CryptoUtils(rsa, ecdsa);

            token.RsaSignature   = cryptoUtils.SignDataRSA(message.ToArray());
            token.EcdsaSignature = cryptoUtils.SignDataECDSA(message.ToArray());

            var signature = cryptoUtils.SignDataECDSA(message.ToArray());

            Assert.True(CryptoUtils.VerifySignatureECDSA(message.ToArray(), ecdsa.PubKey, Encoding.UTF8.GetString(signature)));
            Assert.True(token.VerifySignatures());
        }
Exemple #25
0
        public void RegistrationStoreAddTest()
        {
            var rsa   = new RsaKey();
            var ecdsa = new Key().GetBitcoinSecret(Network.ImpleumMain);

            var token = new RegistrationToken(255,
                                              "1BvBMSEYstWetqTFn5Au4m4GFg7xJaNVN2",
                                              IPAddress.Parse("127.0.0.1"),
                                              IPAddress.Parse("2001:0db8:85a3:0000:0000:8a2e:0370:7334"),
                                              "0123456789ABCDEF",
                                              "",
                                              37123,
                                              ecdsa.PubKey);

            var cryptoUtils = new CryptoUtils(rsa, ecdsa);

            token.RsaSignature   = cryptoUtils.SignDataRSA(token.GetHeaderBytes().ToArray());
            token.EcdsaSignature = cryptoUtils.SignDataECDSA(token.GetHeaderBytes().ToArray());

            RegistrationRecord record = new RegistrationRecord(DateTime.Now,
                                                               Guid.NewGuid(),
                                                               "137cc93a23383252348de58e53e193db471099e78ef89edf1fdea6ff340a7261",
                                                               "0100000027c16c59051604707fcfc75e7ab33decbe72e72baff44ad2b38b78a13929eb5d092df004b20200000048473044022067c3c50f13a1b68402549c6a049a9298d8de03e176909cc6b44f9fd9d9db532502203e7416233a125264aef46698b22f429f60be9ed3b2115ec24f0a05de2a4e4cd901feffffff1d92cb2776b3c3cb3e89ad84c38c72fc72646238d23312a6b1931e7980f90f590200000049483045022100d4141e26371a198fb22347e0cc64fd0563ee11640108836e5f427873e4aa0d00022012960447890e151b46a19c2d1d480f7e81e5ceb615c9566be03189108cb08ce401feffffffa23c4e0da07acb439735e6f2a3c7a1ee15521138cc3815fdbac428e1756a3976010000004948304502210083dfda6e8a7584741c79d60a8c69c372789eb28680fdf43fe15e67eb05c7628e022041cde42e79e83c5be5902c035abcde02579e1841473efbbeb5a909d4520a8ea801fefffffff3b56cf319b4b4895beae1e047d77fddcfd8b86a3964226c0d24dda83335e40802000000484730440220219623b855cd1ac0ad43cb3b76097cb52db2d37b4a6a768a5911dfa3571ff4b602203eb843072f746e225e6c7225438f4f4bf012c18f1a1572d4ead288190d8d61cb01feffffff15209f56f6f5d1246f43057ab546be192659a3c88365529667eb3aa364ed4392000000006b483045022100a5791707155d03fb6e770c0dd0924cf08a3bd3b6e0b5713d7d3e84dc5c2e18bc02200370afce15733f5139a018d3ffc5e594e646ce372274818d9780906f9fb3699101210344e875df3990bf55d7218020b09aea6e1383206ec88344847771b3bc0d72251bfeffffff0220188fba000000001976a914b88f742a0a07af27ccfe21de8a40b9f7541f3e0088ac00e87648170000001976a914db0be998354d2139b14e06459d295de03b94fadb88ac90920000",
                                                               token,
                                                               null);
            RegistrationStore store = new RegistrationStore(Path.GetTempFileName());

            Assert.True(store.Add(record));
        }
Exemple #26
0
        public byte[] Unwrap(byte[] encryptedCek, object key, int cekSizeBits, IDictionary <string, object> header)
        {
            var privateKey = Ensure.Type <RSACryptoServiceProvider>(key, "RsaKeyManagement alg expects key to be of RSACryptoServiceProvider type.");

            return(useSha256 ? RsaOaep.Decrypt(encryptedCek, RsaKey.New(privateKey.ExportParameters(true)), CngAlgorithm.Sha256)
                             : privateKey.Decrypt(encryptedCek, useRsaOaepPadding));
        }
Exemple #27
0
        /// <summary>
        /// 核对签名
        /// </summary>
        /// <returns></returns>
        public bool CheckSign(out string errMsg)
        {
            if (string.IsNullOrWhiteSpace(RsaKey))
            {
                errMsg = "rsaKey is null."; return(false);
            }
            if (string.IsNullOrWhiteSpace(Ciphertext))
            {
                errMsg = "ciphertext is null."; return(false);
            }
            if (Timestamp == 0)
            {
                errMsg = "timestamp is null."; return(false);
            }
            if (string.IsNullOrWhiteSpace(Sign))
            {
                errMsg = "sign is null."; return(false);
            }

            //var st = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(Timestamp);
            //if (Math.Abs(st.Days) >= 1) { errMsg = "timestamp is error."; return false; }

            var txt  = $"{Ciphertext.ToSafeString()}|{RsaKey.ToSafeString()}|{Timestamp.ToSafeString()}";
            var hash = HashUtil.GetMd5String(txt);

            if (Sign.ToUpper() != hash)
            {
                errMsg = "sign is error.";
                return(false);
            }
            errMsg = null;
            return(true);
        }
        public async Task DecryptMessageTest_KeyMismatch()
        {
            var testMessage     = "Fake Message";
            var testMessageBody = Encoding.Default.GetBytes(testMessage);
            var message         = new Message(testMessageBody);

            using (var rsaProvider = new RSACryptoServiceProvider(4_096))
            {
                rsaProvider.PersistKeyInCsp = false;
                using (var rsaKey = new RsaKey("Test Key", rsaProvider))
                    using (var rsaKey2 = new RsaKey("Test Key 2", rsaProvider))
                    {
                        var encryptionPolicy = new EncryptionPolicy(rsaKey, null);
                        var encryptedMessage = await message.EncryptAsync(encryptionPolicy, CancellationToken.None).ConfigureAwait(false);

                        var mockKeyResolver = Substitute.For <IKeyResolver>();
                        mockKeyResolver.ResolveKeyAsync("Test Key", CancellationToken.None).Returns(rsaKey2);

                        var decryptionPolicy = new EncryptionPolicy(o =>
                        {
                            o.EncryptionKey = (token) => mockKeyResolver.ResolveKeyAsync("Test Key", token);
                        });

                        var decryptedMessage = await encryptedMessage.DecryptAsync(decryptionPolicy, CancellationToken.None).ConfigureAwait(false);
                    }
            }
        }
            public void CertificateSignedIndirectly_Should_FindIntermediateCertificateViaLocator()
            {
                // Arrange
                var intermediateKey               = RsaKey.Generate();
                var intermediateCertificate       = intermediateKey.DeriveCertificate();
                var signedIntermediateCertificate = ScenarioRsa.DefaultSignerKey.Sign((RsaCertificate)intermediateCertificate);
                var key               = RsaKey.Generate();
                var certificate       = key.DeriveCertificate();
                var signedCertificate = intermediateKey.Sign((RsaCertificate)certificate);

                var scenario = new Scenario3();
                var lookedUpIntermediateCertificate = false;

                Mock.Get(scenario.CertificateLocator)
                .Setup(m => m.Get(It.IsAny <IHash>()))
                .Returns <IHash>((_hash) =>
                {
                    if (_hash.Hash.SequenceEqual(intermediateCertificate.Hash.Hash))
                    {
                        lookedUpIntermediateCertificate = true;
                        return(signedIntermediateCertificate);
                    }
                    else
                    {
                        return(null);
                    }
                });

                // Act
                // Assert
                scenario.ChainWithLocator.Verify(signedCertificate);
                lookedUpIntermediateCertificate.Should().BeTrue();
            }
            public void CertificateSignedWithUnlocatableCertificate_ShouldThrow_TrustException()
            {
                // Arrange
                var intermediateKey               = RsaKey.Generate();
                var intermediateCertificate       = intermediateKey.DeriveCertificate();
                var signedIntermediateCertificate = ScenarioRsa.DefaultSignerKey.Sign((RsaCertificate)intermediateCertificate);
                var key               = RsaKey.Generate();
                var certificate       = key.DeriveCertificate();
                var signedCertificate = intermediateKey.Sign((RsaCertificate)certificate);

                var scenario = new Scenario3();
                var lookedUpIntermediateCertificate = false;

                Mock.Get(scenario.CertificateLocator)
                .Setup(m => m.Get(It.IsAny <IHash>()))
                .Returns <IHash>((_hash) =>
                {
                    lookedUpIntermediateCertificate = true;
                    return(null);
                });

                // Act
                // Assert
                Assert.Throws <TrustException>(() => scenario.ChainWithLocator.Verify(signedCertificate));
                lookedUpIntermediateCertificate.Should().BeTrue();
            }
Exemple #31
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RsaCipher"/> class.
        /// </summary>
        /// <param name="key">The RSA key.</param>
        public RsaCipher(RsaKey key)
        {
            if (key == null)
                throw new ArgumentNullException("key");

            _key = key;
            _isPrivate = !_key.D.IsZero;
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="RsaDigitalSignature"/> class.
 /// </summary>
 /// <param name="rsaKey">The RSA key.</param>
 public RsaDigitalSignature(RsaKey rsaKey)
     : base(new ObjectIdentifier(1, 3, 14, 3, 2, 26), new RsaCipher(rsaKey))
 {
     this._hash = new SHA1Hash();
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="RsaDigitalSignature"/> class.
 /// </summary>
 /// <param name="rsaKey">The RSA key.</param>
 public RsaDigitalSignature(RsaKey rsaKey)
     : base(new ObjectIdentifier(1, 3, 14, 3, 2, 26), new RsaCipher(rsaKey))
 {
     this._hash = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha1).CreateHash();
 }
Exemple #34
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RsaDigitalSignature"/> class.
 /// </summary>
 /// <param name="rsaKey">The RSA key.</param>
 public RsaDigitalSignature(RsaKey rsaKey)
     : base(new ObjectIdentifier(1, 3, 14, 3, 2, 26), new RsaCipher(rsaKey))
 {
     _hash = CryptoAbstraction.CreateSHA1();
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="RsaDigitalSignature"/> class.
 /// </summary>
 /// <param name="rsaKey">The RSA key.</param>
 public RsaDigitalSignature(RsaKey rsaKey)
     : base(new ObjectIdentifier(1, 3, 14, 3, 2, 26), new RsaCipher(rsaKey))
 {
     _hash = HashAlgorithmFactory.CreateSHA1();
 }