Пример #1
0
        protected override AsymmetricAlgorithm LoadKey(ReadOnlyMemory <byte> pkcs8)
        {
            PrivateKeyInfoAsn   privateKeyInfo = PrivateKeyInfoAsn.Decode(pkcs8, AsnEncodingRules.BER);
            AsymmetricAlgorithm key;

            switch (privateKeyInfo.PrivateKeyAlgorithm.Algorithm.Value)
            {
            case Oids.Rsa:
                key = new RSAOpenSsl();
                break;

            case Oids.Dsa:
                key = new DSAOpenSsl();
                break;

            case Oids.EcDiffieHellman:
            case Oids.EcPublicKey:
                key = new ECDiffieHellmanOpenSsl();
                break;

            default:
                throw new CryptographicException(
                          SR.Cryptography_UnknownAlgorithmIdentifier,
                          privateKeyInfo.PrivateKeyAlgorithm.Algorithm.Value);
            }

            key.ImportPkcs8PrivateKey(pkcs8.Span, out int bytesRead);

            if (bytesRead != pkcs8.Length)
            {
                throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
            }

            return(key);
        }
Пример #2
0
        private static DSA BuildDsaPublicKey(byte[] encodedKeyValue, byte[] encodedParameters)
        {
            SubjectPublicKeyInfoAsn spki = new SubjectPublicKeyInfoAsn
            {
                Algorithm = new AlgorithmIdentifierAsn {
                    Algorithm = Oids.Dsa, Parameters = encodedParameters
                },
                SubjectPublicKey = encodedKeyValue,
            };

            AsnWriter writer = new AsnWriter(AsnEncodingRules.DER);

            spki.Encode(writer);

            DSA dsa = new DSAOpenSsl();

            try
            {
                dsa.ImportSubjectPublicKeyInfo(writer.Encode(), out _);
                return(dsa);
            }
            catch (Exception)
            {
                dsa.Dispose();
                throw;
            }
        }
 public void DefaultConstructors(CspParameters cspParameters)
 {
     var dsa1 = new DSACng();                                // Compliant - default is 2048
     var dsa2 = new DSACryptoServiceProvider();              // Noncompliant - default is 1024
     var dsa3 = new DSACryptoServiceProvider(cspParameters); // Noncompliant - default is 1024
     var dsa4 = new DSAOpenSsl();                            // Compliant - default is 2048
 }
Пример #4
0
        private static DSA BuildDsaPublicKey(byte[] encodedKey, byte[] encodedParameters)
        {
            // Dss-Parms ::= SEQUENCE {
            //   p INTEGER,
            //   q INTEGER,
            //   g INTEGER
            // }

            // The encodedKey value is a DER INTEGER representing the Y value

            DerSequenceReader parametersReader = new DerSequenceReader(encodedParameters);
            DerSequenceReader keyReader        = DerSequenceReader.CreateForPayload(encodedKey);

            DSAParameters parameters = new DSAParameters();

            // While this could use the object initializer, the read modifies the data stream, so
            // leaving these in flat call for clarity.
            parameters.P = parametersReader.ReadIntegerBytes();
            parameters.Q = parametersReader.ReadIntegerBytes();
            parameters.G = parametersReader.ReadIntegerBytes();
            parameters.Y = keyReader.ReadIntegerBytes();

            // Make the structure look like it would from Windows / .NET Framework
            TrimPaddingByte(ref parameters.P);
            TrimPaddingByte(ref parameters.Q);

            PadOrTrim(ref parameters.G, parameters.P.Length);
            PadOrTrim(ref parameters.Y, parameters.P.Length);

            DSA dsa = new DSAOpenSsl();

            dsa.ImportParameters(parameters);
            return(dsa);
        }
Пример #5
0
 public static void VerifyDuplicateKey_DistinctHandles()
 {
     using (DSAOpenSsl first = new DSAOpenSsl())
         using (SafeEvpPKeyHandle firstHandle = first.DuplicateKeyHandle())
             using (SafeEvpPKeyHandle firstHandle2 = first.DuplicateKeyHandle())
             {
                 Assert.NotSame(firstHandle, firstHandle2);
             }
 }
Пример #6
0
 public static void VerifyParameterCtor()
 {
     using (DSA dsa = new DSAOpenSsl(DSATestData.Dsa576Parameters))
     {
         DSAImportExport.AssertKeyEquals(
             DSATestData.Dsa576Parameters,
             dsa.ExportParameters(true));
     }
 }
Пример #7
0
 public static void VerifyDuplicateKey_DistinctHandles()
 {
     using (DSAOpenSsl first = new DSAOpenSsl())
     using (SafeEvpPKeyHandle firstHandle = first.DuplicateKeyHandle())
     using (SafeEvpPKeyHandle firstHandle2 = first.DuplicateKeyHandle())
     {
         Assert.NotSame(firstHandle, firstHandle2);
     }
 }
 public void NonCompliantKeySizeConstructors(CspParameters parameters)
 {
     var dsa1 = new DSACng(512);                                // Noncompliant {{Use a key length of at least 2048 bits for DSA cipher algorithm.}}
     var dsa2 = new DSACryptoServiceProvider(512);              // Noncompliant {{Use a key length of at least 2048 bits for DSA cipher algorithm.}}
     var dsa3 = new DSACryptoServiceProvider(1024, parameters); // Noncompliant
     var dsa4 = new DSACryptoServiceProvider(3072);             // Noncompliant - this is not valid
     var dsa5 = new DSACryptoServiceProvider(2048, parameters); // Noncompliant - this is not valid
     var dsa6 = new DSAOpenSsl(1024);                           // Noncompliant
 }
        public void CompliantKeySizeSet()
        {
            var dsa1 = new DSACng();

            dsa1.KeySize = 3072;

            var dsa2 = new DSAOpenSsl();

            dsa2.KeySize = 3072;
        }
Пример #10
0
        public static void VerifyDuplicateKey_InvalidHandle()
        {
            using (DSAOpenSsl dsa = new DSAOpenSsl())
            {
                SafeEvpPKeyHandle pkey = dsa.DuplicateKeyHandle();

                using (pkey)
                {
                }

                Assert.Throws<ArgumentException>(() => new DSAOpenSsl(pkey));
            }
        }
        public void NoncompliantKeySizeSet()
        {
            var dsa1 = new DSACng();

            dsa1.KeySize = 512;                        // Noncompliant {{Use a key length of at least 2048 bits for DSA cipher algorithm.}}

            var dsa2 = new DSACryptoServiceProvider(); // Noncompliant

            dsa2.KeySize = 2048;                       // Noncompliant {{Use a key length of at least 2048 bits for DSA cipher algorithm. This assignment does not update the underlying key size.}}
            var dsa3 = new DSAOpenSsl();

            dsa3.KeySize = 1024; // Noncompliant
        }
Пример #12
0
        public static void VerifyDuplicateKey_InvalidHandle()
        {
            using (DSAOpenSsl dsa = new DSAOpenSsl())
            {
                SafeEvpPKeyHandle pkey = dsa.DuplicateKeyHandle();

                using (pkey)
                {
                }

                AssertExtensions.Throws <ArgumentException>("pkeyHandle", () => new DSAOpenSsl(pkey));
            }
        }
Пример #13
0
        public static void VerifyDuplicateKey_ValidHandle()
        {
            byte[] data = ByteUtils.RepeatByte(0x71, 11);

            using (DSAOpenSsl first = new DSAOpenSsl())
            using (SafeEvpPKeyHandle firstHandle = first.DuplicateKeyHandle())
            {
                using (DSA second = new DSAOpenSsl(firstHandle))
                {
                    byte[] signed = second.SignData(data, HashAlgorithmName.SHA512);
                    Assert.True(first.VerifyData(data, signed, HashAlgorithmName.SHA512));
                }
            }
        }
Пример #14
0
        public static void VerifyDuplicateKey_ValidHandle()
        {
            byte[] data = ByteUtils.RepeatByte(0x71, 11);

            using (DSAOpenSsl first = new DSAOpenSsl())
                using (SafeEvpPKeyHandle firstHandle = first.DuplicateKeyHandle())
                {
                    using (DSA second = new DSAOpenSsl(firstHandle))
                    {
                        byte[] signed = second.SignData(data, HashAlgorithmName.SHA512);
                        Assert.True(first.VerifyData(data, signed, HashAlgorithmName.SHA512));
                    }
                }
        }
Пример #15
0
        public ICertificatePal CopyWithPrivateKey(DSA privateKey)
        {
            DSAOpenSsl typedKey = privateKey as DSAOpenSsl;

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

            DSAParameters dsaParameters = privateKey.ExportParameters(true);

            using (PinAndClear.Track(dsaParameters.X))
                using (typedKey = new DSAOpenSsl(dsaParameters))
                {
                    return(CopyWithPrivateKey((SafeEvpPKeyHandle)typedKey.DuplicateKeyHandle()));
                }
        }
Пример #16
0
        private static DSA BuildDsaPublicKey(byte[] encodedKey, byte[] encodedParameters)
        {
            SubjectPublicKeyInfoAsn spki = new SubjectPublicKeyInfoAsn
            {
                Algorithm = new AlgorithmIdentifierAsn {
                    Algorithm = new Oid(Oids.Dsa), Parameters = encodedParameters
                },
                SubjectPublicKey = encodedKey,
            };

            using (AsnWriter writer = new AsnWriter(AsnEncodingRules.DER))
            {
                DSA dsa = new DSAOpenSsl();
                spki.Encode(writer);
                dsa.ImportSubjectPublicKeyInfo(writer.EncodeAsSpan(), out _);
                return(dsa);
            }
        }
Пример #17
0
        public static void VerifyDuplicateKey_RefCounts()
        {
            byte[] data = ByteUtils.RepeatByte(0x74, 11);
            byte[] signature;
            DSA second;

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

            // Now show that second still works, despite first and firstHandle being Disposed.
            using (second)
            {
                Assert.True(second.VerifyData(data, signature, HashAlgorithmName.SHA384));
            }
        }
Пример #18
0
        public static void VerifyDuplicateKey_RefCounts()
        {
            byte[] data = ByteUtils.RepeatByte(0x74, 11);
            byte[] signature;
            DSA    second;

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

            // Now show that second still works, despite first and firstHandle being Disposed.
            using (second)
            {
                Assert.True(second.VerifyData(data, signature, HashAlgorithmName.SHA384));
            }
        }
Пример #19
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));
        }
Пример #20
0
        public static void Main(string[] args)
        {
            var hello = DSAOpenSsl.Create();

            Console.WriteLine(DSAOpenSsl.Create());



//            var account = new BankAccount("saviour gidi", 50000);
//            account.MakeWithdrawal(500, DateTime.Now, "saviour", "rent payment");
//            Console.WriteLine(account.Balance);
//
//            account.MakeDeposit(100, DateTime.Now, "friend paid me back");
//            Console.WriteLine(account.Balance);
//
//            Console.WriteLine(account.GetAccountHistory());
//
            // try
            // {
            //     var InvalidAccount = new BankAccount("invalidl", -45);
            // }
            // catch (System.Exception e)
            // {
            //     Console.WriteLine("exception caught ");
            //     Console.WriteLine(e.ToString());
            // }

            /*test for negative balance */
            // try
            // {
            //     account.MakeWithdrawal(750, DateTime.Now, "saviour", "attemp to withdraw");
            // }
            // catch (System.Exception e)
            // {
            //     Console.WriteLine("Exception caught trying to overdraw");
            //     Console.WriteLine(e.ToString());
            // }
        }
 public void CompliantKeySizeConstructors()
 {
     var dsa1 = new DSACng(3072);
     var dsa2 = new DSAOpenSsl(2048);
 }
        /// <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.");
            }
        }