private bool IsSignatureValid(byte[] hash, byte[] signature, CngKey key)
 {
     using (var signingAlg = new RSACng(key))
     {
         return signingAlg.VerifyHash(hash, signature, HashAlgorithmName.SHA384, RSASignaturePadding.Pss);
     }
 }
        public bool SubmitResponse(SignatureMessage message)
        {
            bool retval = false;

            try
            {
                // Use the public key hint to identify which public key to use.
                byte[] challenge;
                byte[] publicKey = DAL.Instance.GetPublicKeyForUser(message.UserId, message.PublicKeyHint, out challenge);

                CngKey pubCngKey = new SubjectPublicKeyInfo(publicKey).GetPublicKey();

                // Validate that the original challenge was signed using the corresponding private key.
                using (RSACng pubKey = new RSACng(pubCngKey))
                {
                    byte[] signature = Convert.FromBase64String(message.Signature);
                    retval = pubKey.VerifyData(challenge, signature, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
                }
            }
            catch (Exception)
            {
            }

            // Return a boolean response to the client
            // TODO:  What should actually be returned is an authentication token (OAuth or equivalent)
            // that the client uses for subsequent authentication requests
            return retval;
        }
 private byte[] AddSignatureToHash(byte[] hash, CngKey key)
 {
     using (var signingAlg = new RSACng(key))
     {
         byte[] signed = signingAlg.SignHash(hash, HashAlgorithmName.SHA384, RSASignaturePadding.Pss);
         return signed;
     }
 }
Esempio n. 4
0
        private static void TestSignVerifyDataRoundTrip(byte[] message, HashAlgorithmName hashAlgorithm, RSASignaturePadding paddingMode, int expectedSignatureLength)
        {
            using (RSA rsa = new RSACng())
            {
                byte[] signature = rsa.SignData(message, hashAlgorithm, paddingMode);

                // RSACng.SignHash() is intentionally non-deterministic so we can verify that we got back a signature of the right length
                // but nothing about the contents.
                Assert.Equal(expectedSignatureLength, signature.Length);

                bool verified = rsa.VerifyData(message, signature, hashAlgorithm, paddingMode);
                Assert.True(verified);
            }
        }
Esempio n. 5
0
        private static void TestEncryptDecryptRoundTrip(byte[] plainText, RSAEncryptionPadding paddingMode, int expectedCipherSize)
        {
            using (RSA rsaCng = new RSACng())
            {
                byte[] cipher = rsaCng.Encrypt(plainText, paddingMode);

                // RSACng.Encrypt() is intentionally non-deterministic so we can verify that we got back a cipher of the right length
                // but nothing about the contents.
                Assert.Equal(expectedCipherSize, cipher.Length);

                // But we can test to see that it decrypts back to the original.
                byte[] plainTextAgain = rsaCng.Decrypt(cipher, paddingMode);
                Assert.Equal<byte>(plainText, plainTextAgain);
            }
        }
Esempio n. 6
0
        static void Main(string[] args)
        {
            string dato = "Este texto se va a firmar";


            Console.Write("Enter your password: "******"");
            string filename = "";

            if (args.Length == 0)
            {
                filename = "temp";
            }
            else
            {
                filename = args[0];
            }

            X509Certificate2 cert = LoadCertificate(filename, password);


            Console.WriteLine("HasPrivateKey: " + cert.HasPrivateKey);

            RSACng privatekey = (RSACng)cert.GetRSAPrivateKey();

            string firma = SignData(dato, privatekey);

            Console.WriteLine("firma: " + firma);


            System.Security.Cryptography.RSACng publickey = (RSACng)cert.GetRSAPrivateKey();

            bool verificado = VerifyData(dato, firma, publickey.ExportParameters(false));

            Console.WriteLine("Fin!!! : " + verificado);
        }
        public async Task<bool> SubmitResponse(SignatureMessage message)
        {
            bool retval = false;

            try
            {
                string challenge;
                JsonWebKey publicKey = _credentialService.GetPublicKeyForUser(message.UserId, message.PublicKeyHint, out challenge);

                var decodedClientData = message.ClientData.Rfc4648Base64UrlDecode();
                var decodedAuthnrData = message.AuthnrData.Rfc4648Base64UrlDecode();

                var clientDataJson = Encoding.UTF8.GetString(decodedClientData);
                var clientData = JsonConvert.DeserializeObject<ClientData>(clientDataJson);
                if (clientData.Challenge != challenge) return false;
                
                var sha256 = SHA256.Create();
                var hashedClientData = sha256.ComputeHash(decodedClientData);
                var buffer = new byte[decodedAuthnrData.Length + hashedClientData.Length];
                decodedAuthnrData.CopyTo(buffer, 0);
                hashedClientData.CopyTo(buffer, decodedAuthnrData.Length);

                var publicKeyInfo = new RSAParameters();
                publicKeyInfo.Modulus = publicKey.N.Rfc4648Base64UrlDecode();
                publicKeyInfo.Exponent = publicKey.E.Rfc4648Base64UrlDecode();
                var rsa = new RSACng();
                rsa.ImportParameters(publicKeyInfo);

                byte[] signature = message.Signature.Rfc4648Base64UrlDecode();
                retval = rsa.VerifyData(buffer, signature, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
                if (retval)
                {
                    var user = _signInService.FindBySubject(message.UserId);
                    await IssueCookie(user, "idsvr", "fido");
                }
            }
            catch (Exception)
            { }
            
            return retval;
        }
Esempio n. 8
0
        private static void RSACng_Ctor_UnusualKeysize(
            int expectedKeySize,
            byte[] keyBlob,
            RSAParameters expectedParameters)
        {
            // Pre-condition: Creating a key of this size will fail
            Assert.Throws<CryptographicException>(() => new RSACng(expectedKeySize));

            using (CngKey cngKey = CngKey.Import(keyBlob, new CngKeyBlobFormat("RSAPRIVATEBLOB")))
            using (RSACng rsaCng = new RSACng(cngKey))
            {
                Assert.Equal(expectedKeySize, rsaCng.KeySize);

                RSAParameters exported = rsaCng.ExportParameters(false);

                Assert.Equal(expectedParameters.Modulus, exported.Modulus);
                Assert.Equal(expectedParameters.Exponent, exported.Exponent);
            }
        }
Esempio n. 9
0
 public static void CreateEcdsaFromRsaKey_Fails()
 {
     using (RSACng rsaCng = new RSACng())
     {
         Assert.Throws<ArgumentException>(() => new ECDsaCng(rsaCng.Key));
     }
 }
Esempio n. 10
0
 static byte[] Encrypt(CngKey key, byte[] plainText)
 {
     var rsa = new RSACng(key);
       return rsa.Encrypt(plainText, RSAEncryptionPadding.Pkcs1);
 }
        /// <summary>
        /// Gets the public Key size in bytes
        /// </summary>
        /// <param name="rsaCngProvider">RSA CNG Provider.</param>
        /// <returns>Key size in bytes</returns>
        private int GetKeySize(RSACng rsaCngProvider)
        {
            Debug.Assert(rsaCngProvider != null);

            return rsaCngProvider.KeySize / 8; // Convert from bits to byte
        }
        /// <summary>
        /// Verifies the given RSA PKCSv1.5 signature.
        /// </summary>
        /// <param name="dataToVerify"></param>
        /// <param name="signature"></param>
        /// <param name="rsaCngProvider">RSA CNG Provider.</param>
        /// <returns>true if signature is valid, false if it is not valid</returns>
        private bool RSAVerifySignature(byte[] dataToVerify, byte[] signature, RSACng rsaCngProvider)
        {
            Debug.Assert((dataToVerify != null) && (dataToVerify.Length != 0));
            Debug.Assert((signature != null) && (signature.Length != 0));
            Debug.Assert(rsaCngProvider != null);

            return rsaCngProvider.VerifyData(dataToVerify, signature, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
        }
        /// <summary>
        /// Generates signature based on RSA PKCS#v1.5 scheme using a specified CNG Key. 
        /// </summary>
        /// <param name="dataToSign">Text to sign.</param>
        /// <param name="rsaCngProvider">RSA CNG Provider.</param>
        /// <returns>Signature</returns>
        private byte[] RSASignHashedData(byte[] dataToSign, RSACng rsaCngProvider)
        {
            Debug.Assert((dataToSign != null) && (dataToSign.Length != 0));
            Debug.Assert(rsaCngProvider != null);

            return rsaCngProvider.SignData(dataToSign, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
        }
        /// <summary>
        /// Decrypt the text using the specified CNG key.
        /// </summary>
        /// <param name="rsaCngProvider">RSA CNG Provider.</param>
        /// <param name="encryptedColumnEncryptionKey">Encrypted Column Encryption Key.</param>
        /// <returns>Returns the decrypted plaintext Column Encryption Key or throws an exception if there are any errors.</returns>
        private byte[] RSADecrypt(RSACng rsaCngProvider, byte[] encryptedColumnEncryptionKey)
        {
            Debug.Assert((encryptedColumnEncryptionKey != null) && (encryptedColumnEncryptionKey.Length != 0));
            Debug.Assert(rsaCngProvider != null);

            return rsaCngProvider.Decrypt(encryptedColumnEncryptionKey, RSAEncryptionPadding.OaepSHA1);
        }
        /// <summary>
        /// Encrypt the text using specified CNG key.
        /// </summary>
        /// <param name="rsaCngProvider">RSA CNG Provider.</param>
        /// <param name="columnEncryptionKey">Plain text Column Encryption Key.</param>
        /// <returns>Returns an encrypted blob or throws an exception if there are any errors.</returns>
        private byte[] RSAEncrypt(RSACng rsaCngProvider, byte[] columnEncryptionKey)
        {
            Debug.Assert(columnEncryptionKey != null);
            Debug.Assert(rsaCngProvider != null);

            return rsaCngProvider.Encrypt(columnEncryptionKey, RSAEncryptionPadding.OaepSHA1);
        }
Esempio n. 16
0
 static byte[] Decrypt(CngKey key, byte[] cipherText)
 {
     var rsa = new RSACng(key);
       return rsa.Decrypt(cipherText, RSAEncryptionPadding.Pkcs1);
 }
Esempio n. 17
0
 public static void ImportExportPublicOnly()
 {
     using (RSA rsa = new RSACng())
     {
         rsa.ImportParameters(TestData.TestRsaKeyPair);
         RSAParameters reExported = rsa.ExportParameters(includePrivateParameters: false);
         Assert.Null(reExported.D);
         Assert.Null(reExported.DP);
         Assert.Null(reExported.DQ);
         Assert.Null(reExported.InverseQ);
         Assert.Null(reExported.P);
         Assert.Null(reExported.Q);
         Assert.Equal<byte>(TestData.TestRsaKeyPair.Exponent, reExported.Exponent);
         Assert.Equal<byte>(TestData.TestRsaKeyPair.Modulus, reExported.Modulus);
     }
 }
Esempio n. 18
0
        public static void ImportExport()
        {
            using (RSA rsa = new RSACng())
            {
                rsa.ImportParameters(TestData.TestRsaKeyPair);
                RSAParameters reExported;

                // This is the current 4.6 behavior.
                Assert.Throws<CryptographicException>(() => reExported = rsa.ExportParameters(includePrivateParameters: true));
                //AssertRSAParametersEquals(TestData.TestRsaKeyPair, reExported);
            }
        }
Esempio n. 19
0
        private static void TestSignAndVerifyDataFromStream(int messageSize)
        {
            RSASignaturePadding padding = RSASignaturePadding.Pkcs1;
            byte[] message = new byte[messageSize];
            byte b = 5;
            for (int i = 0; i < message.Length; i++)
            {
                message[i] = b;
                b = (byte)((b << 4) | (i & 0xf));
            }

            byte[] hash = SHA1.Create().ComputeHash(message);
            Stream stream = new MemoryStream(message);

            using (RSA rsa = new RSACng())
            {
                byte[] signature = rsa.SignData(stream, HashAlgorithmName.SHA1, padding);

                // Since the unique codepath being tested here is HashData(Stream...), the interesting test is to see if HashData(Stream...)
                // computed the right hash. The easiest way to test that is to compute the hash ourselves and call VerifyHash.
                bool verified = rsa.VerifyHash(hash, signature, HashAlgorithmName.SHA1, padding);
                Assert.True(verified);

                stream = new MemoryStream(message);
                verified = rsa.VerifyData(stream, signature, HashAlgorithmName.SHA1, padding);
                Assert.True(verified);
            }
        }