Example #1
0
 public static void VerifyDuplicateKey_DistinctHandles()
 {
     using (RSAOpenSsl first = new RSAOpenSsl())
     using (SafeEvpPKeyHandle firstHandle = first.DuplicateKeyHandle())
     using (SafeEvpPKeyHandle firstHandle2 = first.DuplicateKeyHandle())
     {
         Assert.NotSame(firstHandle, firstHandle2);
     }
 }
Example #2
0
        public static void VerifyDuplicateKey_InvalidHandle()
        {
            using (RSAOpenSsl rsa = new RSAOpenSsl())
            {
                SafeEvpPKeyHandle pkey = rsa.DuplicateKeyHandle();

                using (pkey)
                {
                }

                Assert.Throws<ArgumentException>(() => new RSAOpenSsl(pkey));
            }
        }
        public void NoncompliantKeySizeSet()
        {
            var rsa1 = new RSACng();

            rsa1.KeySize = 1024;                       // Noncompliant {{Use a key length of at least 2048 bits for RSA cipher algorithm.}}

            var rsa3 = new RSACryptoServiceProvider(); // Noncompliant

            rsa3.KeySize = 2048;                       // Noncompliant {{Use a key length of at least 2048 bits for RSA cipher algorithm. This assignment does not update the underlying key size.}}

            var rsa4 = new RSAOpenSsl();

            rsa4.KeySize = 512; // Noncompliant
        }
Example #4
0
        public static void VerifyDuplicateKey_ValidHandle()
        {
            byte[] data = ByteUtils.RepeatByte(0x71, 11);

            using (RSAOpenSsl first = new RSAOpenSsl())
                using (SafeEvpPKeyHandle firstHandle = first.DuplicateKeyHandle())
                {
                    using (RSA second = new RSAOpenSsl(firstHandle))
                    {
                        byte[] signed = second.SignData(data, HashAlgorithmName.SHA512, RSASignaturePadding.Pkcs1);
                        Assert.True(first.VerifyData(data, signed, HashAlgorithmName.SHA512, RSASignaturePadding.Pkcs1));
                    }
                }
        }
Example #5
0
        public static void VerifyDuplicateKey_ValidHandle()
        {
            byte[] data = ByteUtils.RepeatByte(0x71, 11);

            using (RSAOpenSsl first = new RSAOpenSsl())
            using (SafeEvpPKeyHandle firstHandle = first.DuplicateKeyHandle())
            {
                using (RSA second = new RSAOpenSsl(firstHandle))
                {
                    byte[] signed = second.SignData(data, HashAlgorithmName.SHA512, RSASignaturePadding.Pkcs1);
                    Assert.True(first.VerifyData(data, signed, HashAlgorithmName.SHA512, RSASignaturePadding.Pkcs1));
                }
            }
        }
        private static RSA BuildRsaPublicKey(byte[] encodedData)
        {
            RSA rsa = new RSAOpenSsl();

            try
            {
                rsa.ImportRSAPublicKey(new ReadOnlySpan <byte>(encodedData), out _);
            }
            catch (Exception)
            {
                rsa.Dispose();
                throw;
            }
            return(rsa);
        }
        private UserConnection ProcessClient(Socket s)
        {
            var ss = Encoding.ASCII.GetBytes("aaaa can you see this??");

            s.Send(ss);
            UserConnection conn = new UserConnection();

            conn.Sock = s;
            conn.Aes  = new AesCryptoServiceProvider();
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                using (RSACng rsa = new RSACng(3072))
                {
                    conn.Sock.Send(rsa.ExportRSAPublicKey());
                    var aesKey = new byte[384];
                    conn.Sock.Receive(aesKey);
                    conn.Aes.Key = rsa.Decrypt(aesKey, RSAEncryptionPadding.Pkcs1);
                }
            }
            else
            {
                using (RSAOpenSsl rsa = new RSAOpenSsl(3072))
                {
                    conn.Sock.Send(rsa.ExportRSAPublicKey());
                    var aesKey = new byte[384];
                    conn.Sock.Receive(aesKey);
                    conn.Aes.Key = rsa.Decrypt(aesKey, RSAEncryptionPadding.Pkcs1);
                }
            }
            byte[] encryptedMsg;
            var    header = new byte[20];

            conn.Aes.IV.CopyTo(header, 0);
            using (MemoryStream mem = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(mem, conn.Aes.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    using (StreamWriter sw = new StreamWriter(cs))
                        sw.Write("OK!");
                    encryptedMsg = mem.ToArray();
                }
            }
            BitConverter.GetBytes(encryptedMsg.Length).CopyTo(header, 16);
            conn.Sock.Send(header);
            conn.Sock.Send(encryptedMsg);
            return(conn);
        }
Example #8
0
        public SafeFreeCredentials(X509Certificate certificate, SslProtocols protocols, EncryptionPolicy policy)
            : base(IntPtr.Zero, true)
        {
            Debug.Assert(
                certificate == null || certificate is X509Certificate2,
                "Only X509Certificate2 certificates are supported at this time");

            X509Certificate2 cert = (X509Certificate2)certificate;

            if (cert != null)
            {
                Debug.Assert(cert.HasPrivateKey, "cert.HasPrivateKey");

                using (RSAOpenSsl rsa = (RSAOpenSsl)cert.GetRSAPrivateKey())
                {
                    if (rsa != null)
                    {
                        _certKeyHandle = rsa.DuplicateKeyHandle();
                        Interop.Crypto.CheckValidOpenSslHandle(_certKeyHandle);
                    }
                }

                if (_certKeyHandle == null)
                {
                    using (ECDsaOpenSsl ecdsa = (ECDsaOpenSsl)cert.GetECDsaPrivateKey())
                    {
                        if (ecdsa != null)
                        {
                            _certKeyHandle = ecdsa.DuplicateKeyHandle();
                            Interop.Crypto.CheckValidOpenSslHandle(_certKeyHandle);
                        }
                    }
                }

                if (_certKeyHandle == null)
                {
                    throw new NotSupportedException(SR.net_ssl_io_no_server_cert);
                }

                _certHandle = Interop.Crypto.X509Duplicate(cert.Handle);
                Interop.Crypto.CheckValidOpenSslHandle(_certHandle);
            }

            _protocols = protocols;
            _policy    = policy;
        }
        /// <summary>対称アルゴリズム暗号化サービスプロバイダ生成</summary>
        /// <param name="easa">EnumASymmetricAlgorithm</param>
        /// <param name="certificateFilePath">X.509証明書(*.pfx, *.cer)へのパス</param>
        /// <param name="password">パスワード</param>
        /// <param name="flag">X509KeyStorageFlags</param>
        /// <returns>AsymmetricAlgorithm</returns>
        public static AsymmetricAlgorithm CreateCryptographySP(EnumASymmetricAlgorithm easa,
                                                               string certificateFilePath = "", string password = "",
                                                               X509KeyStorageFlags flag   = X509KeyStorageFlags.DefaultKeySet)
        {
            AsymmetricAlgorithm asa = null;

            if (easa == EnumASymmetricAlgorithm.X509)
            {
                // X.509対応
                X509Certificate2 x509Key = new X509Certificate2(certificateFilePath, password, flag);

                if (string.IsNullOrEmpty(password))
                {
                    asa = x509Key.PublicKey.Key;
                }
                else
                {
                    asa = x509Key.PrivateKey;
                }
            }
            else
            {
                if (easa == EnumASymmetricAlgorithm.RsaCsp)
                {
                    // RSACryptoServiceProviderサービスプロバイダ
                    asa = RSACryptoServiceProvider.Create(); // devps(1703)
                }

#if !NET45
                else if (easa == EnumASymmetricAlgorithm.RsaCng)
                {
                    // RSACngサービスプロバイダ
                    asa = RSACng.Create(); // devps(1703)
                }
#endif
#if NETSTD
                else if (easa == EnumASymmetricAlgorithm.RsaOpenSsl)
                {
                    // RSAOpenSslサービスプロバイダ
                    asa = RSAOpenSsl.Create(); // devps(1703)
                }
#endif
            }
            return(asa);
        }
        private RsaSecurityKey GetSecurityKey(string locationName, string subDistName, string txtFileName)
        {
            string xml = string.Empty;

            if (_properties.ContainsKey(locationName) && _properties.ContainsKey(subDistName))
            {
                var storeLocation = _properties[locationName];
                if (_mappingStrToStoreLocation.ContainsKey(storeLocation))
                {
                    using (var store = new X509Store(_mappingStrToStoreLocation[storeLocation]))
                    {
                        store.Open(OpenFlags.OpenExistingOnly);
                        var certificates = store.Certificates.Find(X509FindType.FindBySubjectDistinguishedName, _properties[subDistName], true);
                        if (certificates.Count > 0)
                        {
                            xml = ((RSACryptoServiceProvider)certificates[0].PrivateKey).ToXmlStringNetCore(false);
                        }
                    }
                }
            }
            else
            {
                var locationPath          = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                var publicKeyLocationPath = Path.Combine(locationPath, txtFileName);
                xml = File.ReadAllText(publicKeyLocationPath);
            }

            RsaSecurityKey rsa = null;

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                var provider = new RSACryptoServiceProvider();
                provider.FromXmlStringNetCore(xml);
                rsa = new RsaSecurityKey(provider);
            }
            else
            {
                var r = new RSAOpenSsl();
                r.FromXmlStringNetCore(xml);
                rsa = new RsaSecurityKey(r);
            }

            return(rsa);
        }
Example #11
0
        public static void VerifyDuplicateKey_RefCounts()
        {
            byte[] data = ByteUtils.RepeatByte(0x74, 11);
            byte[] signature;
            RSA    second;

            using (RSAOpenSsl first = new RSAOpenSsl())
                using (SafeEvpPKeyHandle firstHandle = first.DuplicateKeyHandle())
                {
                    signature = first.SignData(data, HashAlgorithmName.SHA384, RSASignaturePadding.Pkcs1);
                    second    = new RSAOpenSsl(firstHandle);
                }

            // Now show that second still works, despite first and firstHandle being Disposed.
            using (second)
            {
                Assert.True(second.VerifyData(data, signature, HashAlgorithmName.SHA384, RSASignaturePadding.Pkcs1));
            }
        }
Example #12
0
        private static void InsertJsonWebKeys(SimpleIdentityServerContext context)
        {
            if (!context.JsonWebKeys.Any())
            {
                var serializedRsa = string.Empty;
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    using (var provider = new RSACryptoServiceProvider())
                    {
                        serializedRsa = provider.ToXmlStringNetCore(true);
                    }
                }
                else
                {
                    using (var rsa = new RSAOpenSsl())
                    {
                        serializedRsa = rsa.ToXmlStringNetCore(true);
                    }
                }

                context.JsonWebKeys.AddRange(new[]
                {
                    new JsonWebKey
                    {
                        Alg           = AllAlg.RS256,
                        KeyOps        = "0,1",
                        Kid           = "1",
                        Kty           = KeyType.RSA,
                        Use           = Use.Sig,
                        SerializedKey = serializedRsa,
                    },
                    new JsonWebKey
                    {
                        Alg           = AllAlg.RSA1_5,
                        KeyOps        = "2,3",
                        Kid           = "2",
                        Kty           = KeyType.RSA,
                        Use           = Use.Enc,
                        SerializedKey = serializedRsa,
                    }
                });
            }
        }
Example #13
0
        public static void VerifyDuplicateKey_RefCounts()
        {
            byte[] data = ByteUtils.RepeatByte(0x74, 11);
            byte[] signature;
            RSA second;

            using (RSAOpenSsl first = new RSAOpenSsl())
            using (SafeEvpPKeyHandle firstHandle = first.DuplicateKeyHandle())
            {
                signature = first.SignData(data, HashAlgorithmName.SHA384, RSASignaturePadding.Pkcs1);
                second = new RSAOpenSsl(firstHandle);
            }

            // Now show that second still works, despite first and firstHandle being Disposed.
            using (second)
            {
                Assert.True(second.VerifyData(data, signature, HashAlgorithmName.SHA384, RSASignaturePadding.Pkcs1));
            }
        }
Example #14
0
        public byte[] Decrypt(
            byte[] toBeDecrypted,
            JsonWebKey jsonWebKey)
        {
#if UAP
            return(null);
#elif NET46 || NET45
            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.FromXmlString(jsonWebKey.SerializedKey);
                return(rsa.Decrypt(toBeDecrypted, _oaep));
            }
#elif NETSTANDARD
            using (var rsa = new RSAOpenSsl())
            {
                rsa.FromXmlString(jsonWebKey.SerializedKey);
                return(rsa.Decrypt(toBeDecrypted, RSAEncryptionPadding.Pkcs1));
            }
#endif
        }
        public static string ToXmlStringNetCore(this RSAOpenSsl rsa, bool includePrivateParameters = false)
        {
            RSAParameters parameters = rsa.ExportParameters(includePrivateParameters);

            if (includePrivateParameters)
            {
                return(string.Format("<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent><P>{2}</P><Q>{3}</Q><DP>{4}</DP><DQ>{5}</DQ><InverseQ>{6}</InverseQ><D>{7}</D></RSAKeyValue>",
                                     Convert.ToBase64String(parameters.Modulus),
                                     Convert.ToBase64String(parameters.Exponent),
                                     Convert.ToBase64String(parameters.P),
                                     Convert.ToBase64String(parameters.Q),
                                     Convert.ToBase64String(parameters.DP),
                                     Convert.ToBase64String(parameters.DQ),
                                     Convert.ToBase64String(parameters.InverseQ),
                                     Convert.ToBase64String(parameters.D)));
            }

            return(string.Format("<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent></RSAKeyValue>",
                                 Convert.ToBase64String(parameters.Modulus),
                                 Convert.ToBase64String(parameters.Exponent)));
        }
Example #16
0
        public static List <JsonWebKey> GetJsonWebKeys(SharedContext sharedContext)
        {
            var serializedRsa = string.Empty;

#if NET461
            using (var provider = new RSACryptoServiceProvider())
            {
                serializedRsa = provider.ToXmlString(true);
            }
#else
            using (var rsa = new RSAOpenSsl())
            {
                serializedRsa = rsa.ToXmlString(true);
            }
#endif
            return(new List <JsonWebKey>
            {
                sharedContext.EncryptionKey,
                sharedContext.SignatureKey
            });
        }
Example #17
0
 public byte[] Decrypt(
     byte[] toBeDecrypted,
     JsonWebKey jsonWebKey)
 {
     if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
     {
         using (var rsa = new RSACryptoServiceProvider())
         {
             rsa.FromXmlStringNetCore(jsonWebKey.SerializedKey);
             return(rsa.Decrypt(toBeDecrypted, _oaep));
         }
     }
     else
     {
         using (var rsa = new RSAOpenSsl())
         {
             rsa.FromXmlStringNetCore(jsonWebKey.SerializedKey);
             return(rsa.Decrypt(toBeDecrypted, RSAEncryptionPadding.Pkcs1));
         }
     }
 }
Example #18
0
        protected override byte[] ExportPkcs8(
            ICertificatePalCore certificatePal,
            ReadOnlySpan <char> password)
        {
            AsymmetricAlgorithm alg        = null;
            SafeEvpPKeyHandle   privateKey = ((OpenSslX509CertificateReader)certificatePal).PrivateKeyHandle;

            try
            {
                alg = new RSAOpenSsl(privateKey);
            }
            catch (CryptographicException)
            {
            }

            if (alg == null)
            {
                try
                {
                    alg = new ECDsaOpenSsl(privateKey);
                }
                catch (CryptographicException)
                {
                }
            }

            if (alg == null)
            {
                try
                {
                    alg = new DSAOpenSsl(privateKey);
                }
                catch (CryptographicException)
                {
                }
            }

            Debug.Assert(alg != null);
            return(alg.ExportEncryptedPkcs8PrivateKey(password, s_windowsPbe));
        }
        private static void InsertJsonWebKeys(SimpleIdentityServerContext context)
        {
            if (!context.JsonWebKeys.Any())
            {
                var serializedRsa = string.Empty;
#if NET46
                using (var provider = new RSACryptoServiceProvider())
                {
                    serializedRsa = provider.ToXmlString(true);
                }
#else
                using (var rsa = new RSAOpenSsl())
                {
                    serializedRsa = rsa.ToXmlString(true);
                }
#endif

                context.JsonWebKeys.AddRange(new[]
                {
                    new JsonWebKey
                    {
                        Alg           = AllAlg.RS256,
                        KeyOps        = "0,1",
                        Kid           = "1",
                        Kty           = KeyType.RSA,
                        Use           = Use.Sig,
                        SerializedKey = serializedRsa,
                    },
                    new JsonWebKey
                    {
                        Alg           = AllAlg.RSA1_5,
                        KeyOps        = "2,3",
                        Kid           = "2",
                        Kty           = KeyType.RSA,
                        Use           = Use.Enc,
                        SerializedKey = serializedRsa,
                    }
                });
            }
        }
Example #20
0
        public ICertificatePal CopyWithPrivateKey(RSA privateKey)
        {
            RSAOpenSsl typedKey = privateKey as RSAOpenSsl;

            if (typedKey != null)
            {
                return(CopyWithPrivateKey((SafeEvpPKeyHandle)typedKey.DuplicateKeyHandle()));
            }

            RSAParameters rsaParameters = privateKey.ExportParameters(true);

            using (PinAndClear.Track(rsaParameters.D))
                using (PinAndClear.Track(rsaParameters.P))
                    using (PinAndClear.Track(rsaParameters.Q))
                        using (PinAndClear.Track(rsaParameters.DP))
                            using (PinAndClear.Track(rsaParameters.DQ))
                                using (PinAndClear.Track(rsaParameters.InverseQ))
                                    using (typedKey = new RSAOpenSsl(rsaParameters))
                                    {
                                        return(CopyWithPrivateKey((SafeEvpPKeyHandle)typedKey.DuplicateKeyHandle()));
                                    }
        }
Example #21
0
        private RsaSecurityKey GetSecurityKey(string txtFileName)
        {
            var            locationPath          = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            var            publicKeyLocationPath = Path.Combine(locationPath, txtFileName);
            var            xml = File.ReadAllText(publicKeyLocationPath);
            RsaSecurityKey rsa = null;

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                var provider = new RSACryptoServiceProvider();
                provider.FromXmlStringNetCore(xml);
                rsa = new RsaSecurityKey(provider);
            }
            else
            {
                var r = new RSAOpenSsl();
                r.FromXmlStringNetCore(xml);
                rsa = new RsaSecurityKey(r);
            }

            return(rsa);
        }
Example #22
0
        private static void NewCertificate()
        {
            var privateSerializedRsa = string.Empty;
            var publicSerializedRsa  = string.Empty;

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                using (var provider = new RSACryptoServiceProvider())
                {
                    privateSerializedRsa = provider.ToXmlStringNetCore(true);
                    publicSerializedRsa  = provider.ToXmlStringNetCore(false);
                }
            }
            else
            {
                using (var rsa = new RSAOpenSsl())
                {
                    privateSerializedRsa = rsa.ToXmlStringNetCore(true);
                    publicSerializedRsa  = rsa.ToXmlStringNetCore(false);
                }
            }

            var locationPath       = GetLocationPath();
            var publicKeyFilePath  = Path.Combine(locationPath, "puk.txt");
            var privateKeyFilePath = Path.Combine(locationPath, "prk.txt");

            if (File.Exists(publicKeyFilePath))
            {
                File.Delete(publicKeyFilePath);
            }

            if (File.Exists(privateKeyFilePath))
            {
                File.Delete(privateKeyFilePath);
            }

            File.WriteAllText(publicKeyFilePath, publicSerializedRsa);
            File.WriteAllText(privateKeyFilePath, privateSerializedRsa);
        }
        public string SignWithRsa(
            JwsAlg algorithm,
            string serializedKeys,
            string combinedJwsNotSigned)
        {
            if (!_supportedAlgs.Contains(algorithm))
            {
                return(null);
            }

            if (string.IsNullOrWhiteSpace(serializedKeys))
            {
                throw new ArgumentNullException("serializedKeys");
            }

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                using (var rsa = new RSACryptoServiceProvider())
                {
                    var hashMethod      = _mappingWinJwsAlgorithmToRsaHashingAlgorithms[algorithm];
                    var bytesToBeSigned = ASCIIEncoding.ASCII.GetBytes(combinedJwsNotSigned);
                    rsa.FromXmlStringNetCore(serializedKeys);
                    var byteToBeConverted = rsa.SignData(bytesToBeSigned, hashMethod);
                    return(byteToBeConverted.Base64EncodeBytes());
                }
            }
            else
            {
                using (var rsa = new RSAOpenSsl())
                {
                    var hashMethod      = _mappingLinuxJwsAlgorithmToRsaHashingAlgorithms[algorithm];
                    var bytesToBeSigned = ASCIIEncoding.ASCII.GetBytes(combinedJwsNotSigned);
                    rsa.FromXmlStringNetCore(serializedKeys);
                    var byteToBeConverted = rsa.SignData(bytesToBeSigned, 0, bytesToBeSigned.Length, hashMethod, RSASignaturePadding.Pkcs1);
                    return(byteToBeConverted.Base64EncodeBytes());
                }
            }
        }
Example #24
0
        public string SignWithRsa(
            JwsAlg algorithm,
            string serializedKeys,
            string combinedJwsNotSigned)
        {
            if (!_mappingJwsAlgorithmToRsaHashingAlgorithms.ContainsKey(algorithm))
            {
                return(null);
            }

            if (string.IsNullOrWhiteSpace(serializedKeys))
            {
                throw new ArgumentNullException("serializedKeys");
            }

            var hashMethod = _mappingJwsAlgorithmToRsaHashingAlgorithms[algorithm];

#if UAP
            // TODO : Implement
            return(null);
#elif NET46 || NET45
            using (var rsa = new RSACryptoServiceProvider())
            {
                var bytesToBeSigned = ASCIIEncoding.ASCII.GetBytes(combinedJwsNotSigned);
                rsa.FromXmlString(serializedKeys);
                var byteToBeConverted = rsa.SignData(bytesToBeSigned, hashMethod);
                return(byteToBeConverted.Base64EncodeBytes());
            }
#elif NETSTANDARD
            using (var rsa = new RSAOpenSsl())
            {
                var bytesToBeSigned = ASCIIEncoding.ASCII.GetBytes(combinedJwsNotSigned);
                rsa.FromXmlString(serializedKeys);
                var byteToBeConverted = rsa.SignData(bytesToBeSigned, 0, bytesToBeSigned.Length, hashMethod, RSASignaturePadding.Pkcs1);
                return(byteToBeConverted.Base64EncodeBytes());
            }
#endif
        }
        public bool VerifyWithRsa(
            JwsAlg algorithm,
            string serializedKeys,
            string input,
            byte[] signature)
        {
            if (!_supportedAlgs.Contains(algorithm))
            {
                return(false);
            }

            if (string.IsNullOrWhiteSpace(serializedKeys))
            {
                throw new ArgumentNullException("serializedKeys");
            }

            var plainBytes = ASCIIEncoding.ASCII.GetBytes(input);

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                using (var rsa = new RSACryptoServiceProvider())
                {
                    var hashMethod = _mappingWinJwsAlgorithmToRsaHashingAlgorithms[algorithm];
                    rsa.FromXmlStringNetCore(serializedKeys);
                    return(rsa.VerifyData(plainBytes, hashMethod, signature));
                }
            }
            else
            {
                using (var rsa = new RSAOpenSsl())
                {
                    var hashMethod = _mappingLinuxJwsAlgorithmToRsaHashingAlgorithms[algorithm];
                    rsa.FromXmlStringNetCore(serializedKeys);
                    return(rsa.VerifyData(plainBytes, signature, hashMethod, RSASignaturePadding.Pkcs1));
                }
            }
        }
        public static void FromXmlStringNetCore(this RSAOpenSsl rsa, string xmlString)
        {
            RSAParameters parameters = new RSAParameters();
            var           xmlDoc     = new XmlDocument();

            xmlDoc.LoadXml(xmlString);
            if (xmlDoc.DocumentElement.Name.Equals("RSAKeyValue"))
            {
                foreach (XmlNode node in xmlDoc.DocumentElement.ChildNodes)
                {
                    switch (node.Name)
                    {
                    case "Modulus": parameters.Modulus = Convert.FromBase64String(node.InnerText); break;

                    case "Exponent": parameters.Exponent = Convert.FromBase64String(node.InnerText); break;

                    case "P": parameters.P = Convert.FromBase64String(node.InnerText); break;

                    case "Q": parameters.Q = Convert.FromBase64String(node.InnerText); break;

                    case "DP": parameters.DP = Convert.FromBase64String(node.InnerText); break;

                    case "DQ": parameters.DQ = Convert.FromBase64String(node.InnerText); break;

                    case "InverseQ": parameters.InverseQ = Convert.FromBase64String(node.InnerText); break;

                    case "D": parameters.D = Convert.FromBase64String(node.InnerText); break;
                    }
                }
            }
            else
            {
                throw new Exception("Invalid XML RSA key.");
            }

            rsa.ImportParameters(parameters);
        }
Example #27
0
        public bool VerifyWithRsa(
            JwsAlg algorithm,
            string serializedKeys,
            string input,
            byte[] signature)
        {
            if (!_mappingJwsAlgorithmToRsaHashingAlgorithms.ContainsKey(algorithm))
            {
                return(false);
            }

            if (string.IsNullOrWhiteSpace(serializedKeys))
            {
                throw new ArgumentNullException("serializedKeys");
            }

            var plainBytes = ASCIIEncoding.ASCII.GetBytes(input);
            var hashMethod = _mappingJwsAlgorithmToRsaHashingAlgorithms[algorithm];

#if UAP
            // TODO : Implement
            return(false);
#elif NET46 || NET45
            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.FromXmlString(serializedKeys);
                return(rsa.VerifyData(plainBytes, hashMethod, signature));
            }
#elif NETSTANDARD
            using (var rsa = new RSAOpenSsl())
            {
                rsa.FromXmlString(serializedKeys);
                return(rsa.VerifyData(plainBytes, signature, hashMethod, RSASignaturePadding.Pkcs1));
            }
#endif
        }
Example #28
0
        private static void InsertJsonWebKeys(SimpleIdentityServerContext context, SharedContext sharedContext)
        {
            if (!context.JsonWebKeys.Any())
            {
                var serializedRsa = string.Empty;
#if NET461
                using (var provider = new RSACryptoServiceProvider())
                {
                    serializedRsa = provider.ToXmlString(true);
                }
#else
                using (var rsa = new RSAOpenSsl())
                {
                    serializedRsa = rsa.ToXmlString(true);
                }
#endif

                context.JsonWebKeys.AddRange(new[]
                {
                    sharedContext.ModelEncryptionKey,
                    sharedContext.ModelSignatureKey
                });
            }
        }
Example #29
0
        public async Task <bool> Execute()
        {
            var jsonWebKeys = await _jsonWebKeyRepository.GetAllAsync();

            if (jsonWebKeys == null ||
                !jsonWebKeys.Any())
            {
                return(false);
            }

            foreach (var jsonWebKey in jsonWebKeys)
            {
                var serializedRsa = string.Empty;
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    using (var provider = new RSACryptoServiceProvider())
                    {
                        serializedRsa = provider.ToXmlStringNetCore(true);
                    }
                }
                else
                {
                    using (var rsa = new RSAOpenSsl())
                    {
                        serializedRsa = rsa.ToXmlStringNetCore(true);
                    }
                }

                jsonWebKey.SerializedKey = serializedRsa;
                await _jsonWebKeyRepository.UpdateAsync(jsonWebKey);
            }

            await _tokenStore.Clean().ConfigureAwait(false);

            return(true);
        }
 public RSACryptoServiceProvider()
 {
     _defer = new RSAOpenSsl();
 }
        /// <summary>署名・検証サービスプロバイダの生成</summary>
        /// <param name="eaa">EnumDigitalSignAlgorithm</param>
        /// <param name="aa">
        /// AsymmetricAlgorithm
        /// - RSACryptoServiceProvider
        /// - DSACryptoServiceProvider
        /// </param>
        /// <param name="ha">
        /// HashAlgorithm
        /// </param>
        public static void CreateDigitalSignSP(
            EnumDigitalSignAlgorithm eaa, out AsymmetricAlgorithm aa, out HashAlgorithm ha)
        {
            aa = null;
            ha = null;

            // 公開鍵・暗号化サービスプロバイダ
            if (eaa == EnumDigitalSignAlgorithm.RsaCSP_MD5 ||
                eaa == EnumDigitalSignAlgorithm.RsaCSP_SHA1 ||
                eaa == EnumDigitalSignAlgorithm.RsaCSP_SHA256 ||
                eaa == EnumDigitalSignAlgorithm.RsaCSP_SHA384 ||
                eaa == EnumDigitalSignAlgorithm.RsaCSP_SHA512)
            {
                // RSACryptoServiceProviderサービスプロバイダ
                aa = new RSACryptoServiceProvider();

                switch (eaa)
                {
                case EnumDigitalSignAlgorithm.RsaCSP_MD5:
                    ha = MD5.Create();
                    break;

                case EnumDigitalSignAlgorithm.RsaCSP_SHA1:
                    ha = SHA1.Create();
                    break;

                case EnumDigitalSignAlgorithm.RsaCSP_SHA256:
                    ha = SHA256.Create();
                    break;

                case EnumDigitalSignAlgorithm.RsaCSP_SHA384:
                    ha = SHA384.Create();
                    break;

                case EnumDigitalSignAlgorithm.RsaCSP_SHA512:
                    ha = SHA512.Create();
                    break;
                }
            }
#if NETSTD
            else if (eaa == EnumDigitalSignAlgorithm.RsaOpenSsl_MD5 ||
                     eaa == EnumDigitalSignAlgorithm.RsaOpenSsl_SHA1 ||
                     eaa == EnumDigitalSignAlgorithm.RsaOpenSsl_SHA256 ||
                     eaa == EnumDigitalSignAlgorithm.RsaOpenSsl_SHA384 ||
                     eaa == EnumDigitalSignAlgorithm.RsaOpenSsl_SHA512)
            {
                // RSAOpenSslサービスプロバイダ
                aa = new RSAOpenSsl();

                switch (eaa)
                {
                case EnumDigitalSignAlgorithm.RsaOpenSsl_MD5:
                    ha = MD5.Create();
                    break;

                case EnumDigitalSignAlgorithm.RsaOpenSsl_SHA1:
                    ha = SHA1.Create();
                    break;

                case EnumDigitalSignAlgorithm.RsaOpenSsl_SHA256:
                    ha = SHA256.Create();
                    break;

                case EnumDigitalSignAlgorithm.RsaOpenSsl_SHA384:
                    ha = SHA384.Create();
                    break;

                case EnumDigitalSignAlgorithm.RsaOpenSsl_SHA512:
                    ha = SHA512.Create();
                    break;
                }
            }
#endif
            else if (eaa == EnumDigitalSignAlgorithm.DsaCSP_SHA1)
            {
                // DSACryptoServiceProvider
                aa = new DSACryptoServiceProvider();
                ha = SHA1.Create();
            }
#if NETSTD
            else if (eaa == EnumDigitalSignAlgorithm.DsaOpenSsl_SHA1)
            {
                // DSAOpenSslサービスプロバイダ
                aa = new DSAOpenSsl();
                ha = SHA1.Create();
            }
#endif
            else if (
                eaa == EnumDigitalSignAlgorithm.ECDsaCng_P256 ||
                eaa == EnumDigitalSignAlgorithm.ECDsaCng_P384 ||
                eaa == EnumDigitalSignAlgorithm.ECDsaCng_P521)
            {
                // ECDsaCngはCngKeyが土台で、
                // ECDsaCng生成後にオプションとして設定するのではなく
                // CngKeyの生成時にCngAlgorithmの指定が必要であるもよう。
                CngAlgorithm cngAlgorithm = null;
                switch (eaa)
                {
                case EnumDigitalSignAlgorithm.ECDsaCng_P256:
                    cngAlgorithm = CngAlgorithm.ECDsaP256;
                    break;

                case EnumDigitalSignAlgorithm.ECDsaCng_P384:
                    cngAlgorithm = CngAlgorithm.ECDsaP384;
                    break;

                case EnumDigitalSignAlgorithm.ECDsaCng_P521:
                    cngAlgorithm = CngAlgorithm.ECDsaP521;
                    break;
                }
                aa = new ECDsaCng(CngKey.Create(cngAlgorithm));
                ha = null; // ハッシュ無し
            }
#if NETSTD
            else if (
                eaa == EnumDigitalSignAlgorithm.ECDsaOpenSsl_P256 ||
                eaa == EnumDigitalSignAlgorithm.ECDsaOpenSsl_P384 ||
                eaa == EnumDigitalSignAlgorithm.ECDsaOpenSsl_P521)
            {
                ECCurve      eCCurve = ECCurve.NamedCurves.nistP256;
                ECParameters eCParameters;
                ECDsa        eCDsa        = null;
                ECDsaOpenSsl eCDsaOpenSsl = null;

                switch (eaa)
                {
                case EnumDigitalSignAlgorithm.ECDsaOpenSsl_P256:
                    eCCurve = ECCurve.NamedCurves.nistP256;
                    break;

                case EnumDigitalSignAlgorithm.ECDsaOpenSsl_P384:
                    eCCurve = ECCurve.NamedCurves.nistP384;
                    break;

                case EnumDigitalSignAlgorithm.ECDsaOpenSsl_P521:
                    eCCurve = ECCurve.NamedCurves.nistP521;
                    break;
                }

                // https://qiita.com/yoship1639/items/6dd0cc8623d7f3969d78
                if (Environment.OSVersion.Platform == PlatformID.Unix)
                {
                    eCDsa = ECDsa.Create(); // ECDsaOpenSslと思われる。
                    eCDsa.GenerateKey(eCCurve);
                    eCParameters = eCDsa.ExportParameters(true);
                    eCDsaOpenSsl = new ECDsaOpenSsl(eCParameters.Curve);
                    eCDsaOpenSsl.ImportParameters(eCParameters);
                }

                aa = eCDsaOpenSsl;
                ha = null; // ハッシュ無し
            }
#endif
            else
            {
                throw new ArgumentException(
                          PublicExceptionMessage.ARGUMENT_INCORRECT,
                          "EnumDigitalSignAlgorithm parameter is incorrect.");
            }
        }
Example #32
0
        public static RSA DecodeRSAPrivateKey(byte[] privkey, bool isPkcs8)
        {
            byte[] MODULUS, E, D, P, Q, DP, DQ, IQ;

            // ---------  Set up stream to decode the asn.1 encoded RSA private key  ------
            using (var mem = new MemoryStream(privkey))
                using (var binr = new BinaryReader(mem)) //wrap Memory Stream with BinaryReader for easy reading
                {
                    byte   bt       = 0;
                    ushort twobytes = 0;
                    var    elems    = 0;
                    try
                    {
                        twobytes = binr.ReadUInt16();
                        if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
                        {
                            binr.ReadByte();    //advance 1 byte
                        }
                        else if (twobytes == 0x8230)
                        {
                            binr.ReadInt16(); //advance 2 bytes
                        }
                        else
                        {
                            Configuration.Instance.AuthenticationLogger.LogError("RSA decode fail: Expected sequence");
                            return(null);
                        }

                        twobytes = binr.ReadUInt16();
                        if (twobytes != 0x0102) //version number
                        {
                            Configuration.Instance.AuthenticationLogger.LogError("RSA decode fail: Version number mismatch");
                            return(null);
                        }
                        bt = binr.ReadByte();
                        if (bt != 0x00)
                        {
                            Configuration.Instance.AuthenticationLogger.LogError("RSA decode fail: 00 read fail");
                            return(null);
                        }

                        if (isPkcs8)
                        {
                            // if pkcs#8, we need to remove the key from the container
                            bt = binr.ReadByte();
                            if (bt != 0x30)
                            {
                                Configuration.Instance.AuthenticationLogger.LogError("RSA decode fail: PKCS#8 expected sequence");
                                return(null);
                            }
                            bt = binr.ReadByte(); // length in octets, should be 0x0d
                            // skip the container so we can continue with the key
                            // we also skip 11 bytes because that is the pkcs#1 preamble and we're going to assume it's valid
                            binr.BaseStream.Seek(bt + 11, SeekOrigin.Current);
                        }

                        //------  all private key components are Integer sequences ----
                        elems   = GetIntegerSize(binr);
                        MODULUS = binr.ReadBytes(elems);

                        elems = GetIntegerSize(binr);
                        E     = binr.ReadBytes(elems);

                        elems = GetIntegerSize(binr);
                        D     = binr.ReadBytes(elems);

                        elems = GetIntegerSize(binr);
                        P     = binr.ReadBytes(elems);

                        elems = GetIntegerSize(binr);
                        Q     = binr.ReadBytes(elems);

                        elems = GetIntegerSize(binr);
                        DP    = binr.ReadBytes(elems);

                        elems = GetIntegerSize(binr);
                        DQ    = binr.ReadBytes(elems);

                        elems = GetIntegerSize(binr);
                        IQ    = binr.ReadBytes(elems);

                        //Console.WriteLine("showing components ..");
                        //if (verbose)
                        //{
                        //    showBytes("\nModulus", MODULUS);
                        //    showBytes("\nExponent", E);
                        //    showBytes("\nD", D);
                        //    showBytes("\nP", P);
                        //    showBytes("\nQ", Q);
                        //    showBytes("\nDP", DP);
                        //    showBytes("\nDQ", DQ);
                        //    showBytes("\nIQ", IQ);
                        //}

                        // ------- create RSACryptoServiceProvider instance and initialize with public key -----
#if NETSTANDARD1_6
                        RSA RSA;
                        if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ||
                            RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                        {
                            RSA = new RSAOpenSsl();
                        }
                        else
                        {
                            RSA = new RSACng();
                        }
                        var RSAparams = new RSAParameters
                        {
                            Modulus  = MODULUS,
                            Exponent = E,
                            D        = D,
                            P        = P,
                            Q        = Q,
                            DP       = DP,
                            DQ       = DQ,
                            InverseQ = IQ
                        };
                        RSA.ImportParameters(RSAparams);
                        return(RSA);
#else
                        var RSA       = new RSACryptoServiceProvider();
                        var RSAparams = new RSAParameters
                        {
                            Modulus  = MODULUS,
                            Exponent = E,
                            D        = D,
                            P        = P,
                            Q        = Q,
                            DP       = DP,
                            DQ       = DQ,
                            InverseQ = IQ
                        };
                        RSA.ImportParameters(RSAparams);
                        return(RSA);
#endif
                    }
                    catch (Exception ex)
                    {
                        Configuration.Instance.AuthenticationLogger.LogError($"DecodeRSAPrivateKey fail: {ex.Message}");
                        return(null);
                    }
                }
        }
        /// <summary>
        /// DecodePrivateKeyInfo
        /// </summary>
        /// <param name="pkcs8">pkcs8 key</param>
        /// <returns>RSAOpenSsl</returns>
        public static RSAOpenSsl DecodePrivateKeyInfo(byte[] pkcs8)
        {
            // encoded OID sequence for  PKCS #1 rsaEncryption szOID_RSA_RSA = "1.2.840.113549.1.1.1"
            // this byte[] includes the sequence byte and terminal encoded null
            byte[] seqOid = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 };

            // ---------  Set up stream to read the asn.1 encoded SubjectPublicKeyInfo blob  ------
            var memoryStream = new MemoryStream(pkcs8);
            var streamLength = (int)memoryStream.Length;
            var binaryReader = new BinaryReader(memoryStream);    //wrap Memory Stream with BinaryReader for easy reading

            try
            {
                var twoBytes = binaryReader.ReadUInt16();
                if (twoBytes == 0x8130)      //data read as little endian order (actual data order for Sequence is 30 81)
                {
                    binaryReader.ReadByte(); //advance 1 byte
                }
                else if (twoBytes == 0x8230)
                {
                    binaryReader.ReadInt16();   //advance 2 bytes
                }
                else
                {
                    return(null);
                }
                var bt = binaryReader.ReadByte();
                if (bt != 0x02)
                {
                    return(null);
                }

                twoBytes = binaryReader.ReadUInt16();

                if (twoBytes != 0x0001)
                {
                    return(null);
                }
                var seq = binaryReader.ReadBytes(15);
                if (!CompareByteArrays(seq, seqOid))    //make sure Sequence for OID is correct
                {
                    return(null);
                }
                bt = binaryReader.ReadByte();
                if (bt != 0x04) //expect an Octet string
                {
                    return(null);
                }
                bt = binaryReader.ReadByte();       //read next byte, or next 2 bytes is  0x81 or 0x82; otherwise bt is the byte count
                if (bt == 0x81)
                {
                    binaryReader.ReadByte();
                }
                else
                {
                    if (bt == 0x82)
                    {
                        binaryReader.ReadUInt16();
                    }
                }
                //------ at this stage, the remaining sequence should be the RSA private key
                byte[]     rsaPrivateKey = binaryReader.ReadBytes((int)(streamLength - memoryStream.Position));
                RSAOpenSsl rsaOpenSsl    = DecodeRsaPrivateKey(rsaPrivateKey);
                return(rsaOpenSsl);
            }

            catch (Exception)
            {
                return(null);
            }

            finally
            {
                binaryReader.Close();
            }
        }
 public static void VerifyDuplicateKey_RsaHandle()
 {
     using (RSAOpenSsl rsa = new RSAOpenSsl())
     using (SafeEvpPKeyHandle pkey = rsa.DuplicateKeyHandle())
     {
         Assert.ThrowsAny<CryptographicException>(() => new ECDsaOpenSsl(pkey));
     }
 }
        /// <summary>
        /// Parses binary ans.1 RSA private key; returns RSAOpenSsl
        /// </summary>
        /// <param name="privateKey"></param>
        /// <returns></returns>
        public static RSAOpenSsl DecodeRsaPrivateKey(byte[] privateKey)
        {
            // ---------  Set up stream to decode the asn.1 encoded RSA private key  ------
            var memoryStream = new MemoryStream(privateKey);
            var binaryReader = new BinaryReader(memoryStream);    //wrap Memory Stream with BinaryReader for easy reading

            try
            {
                var twoBytes = binaryReader.ReadUInt16();
                if (twoBytes == 0x8130)      //data read as little endian order (actual data order for Sequence is 30 81)
                {
                    binaryReader.ReadByte(); //advance 1 byte
                }
                else if (twoBytes == 0x8230)
                {
                    binaryReader.ReadInt16();   //advance 2 bytes
                }
                else
                {
                    return(null);
                }

                twoBytes = binaryReader.ReadUInt16();
                if (twoBytes != 0x0102) //version number
                {
                    return(null);
                }

                var bt = binaryReader.ReadByte();
                if (bt != 0x00)
                {
                    return(null);
                }

                //------  all private key components are Integer sequences ----
                var elems   = GetIntegerSize(binaryReader);
                var modulus = binaryReader.ReadBytes(elems);

                elems = GetIntegerSize(binaryReader);
                var e = binaryReader.ReadBytes(elems);

                elems = GetIntegerSize(binaryReader);
                var d = binaryReader.ReadBytes(elems);

                elems = GetIntegerSize(binaryReader);
                var p = binaryReader.ReadBytes(elems);

                elems = GetIntegerSize(binaryReader);
                var q = binaryReader.ReadBytes(elems);

                elems = GetIntegerSize(binaryReader);
                var dp = binaryReader.ReadBytes(elems);

                elems = GetIntegerSize(binaryReader);
                var dq = binaryReader.ReadBytes(elems);

                elems = GetIntegerSize(binaryReader);
                var iq = binaryReader.ReadBytes(elems);

                var rsaParameters = new RSAParameters
                {
                    Modulus  = modulus,
                    Exponent = e,
                    D        = d,
                    P        = p,
                    Q        = q,
                    DP       = dp,
                    DQ       = dq,
                    InverseQ = iq
                };

                var rsaOpenSsl = new RSAOpenSsl();
                rsaOpenSsl.ImportParameters(rsaParameters);
                return(rsaOpenSsl);
            }
            catch (Exception)
            {
                return(null);
            }
            finally
            {
                binaryReader.Close();
            }
        }
 public RSACryptoServiceProvider(int dwKeySize)
 {
     _defer = new RSAOpenSsl(dwKeySize);
 }
 public void DefaultConstructors()
 {
     var rsa1 = new RSACng();                   // Compliant - default is 2048
     var rsa2 = new RSACryptoServiceProvider(); // Noncompliant - default is 1024
     var rsa3 = new RSAOpenSsl();               // Compliant - default is 2048
 }
 public RSACryptoServiceProvider(int dwKeySize)
 {
     _defer = new RSAOpenSsl(dwKeySize);
     _legalKeySizesValue = _defer.LegalKeySizes;
 }