Пример #1
0
 public static AsymmetricCipherKeyPair GetDsaKeyPair(DSA dsa)
 {
     return(GetDsaKeyPair(dsa.ExportParameters(true)));
 }
Пример #2
0
        public void ImportKeyNode()
        {
            string keyName             = "Mono::";
            string dsaP                = "rjxsMU368YOCTQejWkiuO9e/vUVwkLtq1jKiU3TtJ53hBJqjFRuTa228vZe+BH2su9RPn/vYFWfQDv6zgBYe3eNdu4Afw+Ny0FatX6dl3E77Ra6Tsd3MmLXBiGSQ1mMNd5G2XQGpbt9zsGlUaexXekeMLxIufgfZLwYp67M+2WM=";
            string dsaQ                = "tf0K9rMyvUrU4cIkwbCrDRhQAJk=";
            string dsaG                = "S8Z+1pGCed00w6DtVcqZLKjfqlCJ7JsugEFIgSy/Vxtu9YGCMclV4ijGEbPo/jU8YOSMuD7E9M7UaopMRcmKQjoKZzoJjkgVFP48Ohxl1f08lERnButsxanx3+OstFwUGQ8XNaGg3KrIoZt1FUnfxN3RHHTvVhjzNSHxMGULGaU=";
            string dsaY                = "LnrxxRGLYeV2XLtK3SYz8RQHlHFZYrtznDZyMotuRfO5uC5YODhSFyLXvb1qB3WeGtF4h3Eo4KzHgMgfN2ZMlffxFRhJgTtH3ctbL8lfQoDkjeiPPnYGhspdJxr0tyZmiy0gkjJG3vwHYrLnvZWx9Wm/unqiOlGBPNuxJ+hOeP8=";
            string dsaJ                = "9RhE5TycDtdEIXxS3HfxFyXYgpy81zY5lVjwD6E9JP37MWEi80BlX6ab1YPm6xYSEoqReMPP9RgGiW6DuACpgI7+8vgCr4i/7VhzModJAA56PwvTu6UMt9xxKU/fT672v8ucREkMWoc7lEey";
            string dsaSeed             = "HxW3N4RHWVgqDQKuGg7iJTUTiCs=";
            string dsaPgenCounter      = "Asw=";
            string rsaModulus          = "9DC4XNdQJwMRnz5pP2a6U51MHCODRilaIoVXqUPhCUb0lJdGroeqVYT84ZyIVrcarzD7Tqs3aEOIa3rKox0N1bxQpZPqayVQeLAkjLLtzJW/ScRJx3uEDJdgT1JnM1FH0GZTinmEdCUXdLc7+Y/c/qqIkTfbwHbRZjW0bBJyExM=";
            string rsaExponent         = "AQAB";
            string x509cert            = "MIICHTCCAYYCARQwDQYJKoZIhvcNAQEEBQAwWDELMAkGA1UEBhMCQ0ExHzAdBgNVBAMTFktleXdpdG5lc3MgQ2FuYWRhIEluYy4xKDAmBgorBgEEASoCCwIBExhrZXl3aXRuZXNzQGtleXdpdG5lc3MuY2EwHhcNOTYwNTA3MDAwMDAwWhcNOTkwNTA3MDAwMDAwWjBYMQswCQYDVQQGEwJDQTEfMB0GA1UEAxMWS2V5d2l0bmVzcyBDYW5hZGEgSW5jLjEoMCYGCisGAQQBKgILAgETGGtleXdpdG5lc3NAa2V5d2l0bmVzcy5jYTCBnTANBgkqhkiG9w0BAQEFAAOBiwAwgYcCgYEAzSP6KuHtmPTp0JM+13qAAkzMwQKvXLYff/pXQm8w0SDFtSEHQCyphsLzZISuPYUu7YW9VLAYKO9q+BvnCxYfkyVPx/iOw7nKmIQOVdAv73h3xXIoX2C/GSvRcqK32D/glzRaAb0EnMh4Rc2TjRXydhARq7hbLp5S3YE+nGTIKZMCAQMwDQYJKoZIhvcNAQEEBQADgYEAMho1ur9DJ9a01Lh25eObTWzAhsl3NbprFi0TRkqwMlOhW1rpmeIMhogXTg3+gqxOR+/7/zms7jXI+lI3CkmtWa3iiqkcxl8f+G9zfs2gMegMvvVN2bKrihK2MHhoEXwN8UlNo/2y6f8d8JH6VIX/M5Dowb+km6RiRr1hElmYQYk=";
            string retrievalElementUri = @"http://www.go-mono.org/";

            string value = $@"<KeyInfo xmlns=""http://www.w3.org/2000/09/xmldsig#"">
                <KeyName>{keyName}</KeyName>
                <KeyValue xmlns=""http://www.w3.org/2000/09/xmldsig#"">
                    <DSAKeyValue>
                        <P>{dsaP}</P>
                        <Q>{dsaQ}</Q>
                        <G>{dsaG}</G>
                        <Y>{dsaY}</Y>
                        <J>{dsaJ}</J>
                        <Seed>{dsaSeed}</Seed>
                        <PgenCounter>{dsaPgenCounter}</PgenCounter>
                    </DSAKeyValue>
                </KeyValue>
                <KeyValue xmlns=""http://www.w3.org/2000/09/xmldsig#"">
                    <RSAKeyValue>
                        <Modulus>{rsaModulus}</Modulus>
                        <Exponent>{rsaExponent}</Exponent>
                    </RSAKeyValue>
                </KeyValue>
                <RetrievalElement URI=""{retrievalElementUri}"" />
                <X509Data xmlns=""http://www.w3.org/2000/09/xmldsig#"">
                    <X509Certificate>{x509cert}</X509Certificate>
                </X509Data>
            </KeyInfo>";

            XmlDocument doc = new XmlDocument();

            doc.LoadXml(value);
            info.LoadXml(doc.DocumentElement);

            Assert.Equal(5, info.Count);
            int i            = 0;
            int pathsCovered = 0;

            foreach (var clause in info)
            {
                i++;

                if (clause is KeyInfoName)
                {
                    pathsCovered |= 1 << 0;

                    var name = clause as KeyInfoName;
                    Assert.Equal(keyName, name.Value);
                }
                else if (clause is DSAKeyValue)
                {
                    pathsCovered |= 1 << 1;

                    var           dsaKV     = clause as DSAKeyValue;
                    DSA           dsaKey    = dsaKV.Key;
                    DSAParameters dsaParams = dsaKey.ExportParameters(false);

                    Assert.Equal(Convert.FromBase64String(dsaP), dsaParams.P);
                    Assert.Equal(Convert.FromBase64String(dsaQ), dsaParams.Q);
                    Assert.Equal(Convert.FromBase64String(dsaG), dsaParams.G);
                    Assert.Equal(Convert.FromBase64String(dsaY), dsaParams.Y);

                    // J is an optimization it should either be null or correct value
                    if (dsaParams.J != null)
                    {
                        Assert.Equal(Convert.FromBase64String(dsaJ), dsaParams.J);
                    }

                    // Seed and Counter are not guaranteed to roundtrip
                    // they should either both be non-null or both null
                    if (dsaParams.Seed != null)
                    {
                        Assert.Equal(Convert.FromBase64String(dsaSeed), dsaParams.Seed);

                        byte[] counter = Convert.FromBase64String(dsaPgenCounter);
                        Assert.InRange(counter.Length, 1, 4);
                        int counterVal = 0;
                        for (int j = 0; j < counter.Length; j++)
                        {
                            counterVal <<= 8;
                            counterVal  |= counter[j];
                        }

                        Assert.Equal(counterVal, dsaParams.Counter);
                    }
                    else
                    {
                        Assert.Null(dsaParams.Seed);
                        Assert.Equal(default(int), dsaParams.Counter);
                    }
                }
                else if (clause is RSAKeyValue)
                {
                    pathsCovered |= 1 << 2;

                    var           rsaKV         = clause as RSAKeyValue;
                    RSA           rsaKey        = rsaKV.Key;
                    RSAParameters rsaParameters = rsaKey.ExportParameters(false);

                    Assert.Equal(Convert.FromBase64String(rsaModulus), rsaParameters.Modulus);
                    Assert.Equal(Convert.FromBase64String(rsaExponent), rsaParameters.Exponent);
                }
                else if (clause is KeyInfoNode)
                {
                    pathsCovered |= 1 << 3;

                    var        keyInfo   = clause as KeyInfoNode;
                    XmlElement keyInfoEl = keyInfo.GetXml();
                    Assert.Equal("RetrievalElement", keyInfoEl.LocalName);
                    Assert.Equal("http://www.w3.org/2000/09/xmldsig#", keyInfoEl.NamespaceURI);
                    Assert.Equal(1, keyInfoEl.Attributes.Count);
                    Assert.Equal("URI", keyInfoEl.Attributes[0].Name);
                    Assert.Equal(retrievalElementUri, keyInfoEl.GetAttribute("URI"));
                }
                else if (clause is KeyInfoX509Data)
                {
                    pathsCovered |= 1 << 4;

                    var x509data = clause as KeyInfoX509Data;
                    Assert.Equal(1, x509data.Certificates.Count);
                    X509Certificate cert = x509data.Certificates[0] as X509Certificate;
                    Assert.NotNull(cert);
                    Assert.Equal(Convert.FromBase64String(x509cert), cert.GetRawCertData());
                }
                else
                {
                    Assert.True(false, $"Unexpected clause type: {clause.GetType().FullName}");
                }
            }

            // 0x1f = b11111, number of ones = 5
            Assert.Equal(0x1f, pathsCovered);
            Assert.Equal(5, i);
        }
Пример #3
0
 public static DsaPublicKeyParameters GetDsaPublicKey(DSA dsa)
 {
     return(DotNetUtilities.GetDsaPublicKey(dsa.ExportParameters(false)));
 }
 public void ExchangeDSAKey()
 {
     DSA dsa = DSA.Create();
     AsymmetricKeyExchangeDeformatter keyex = new RSAPKCS1KeyExchangeDeformatter(dsa);
 }
Пример #5
0
        static public DSA FromCapiPublicKeyBlobDSA(byte[] blob, int offset)
        {
            if (blob == null)
            {
                throw new ArgumentNullException("blob");
            }
            if (offset >= blob.Length)
            {
                throw new ArgumentException("blob is too small.");
            }

            try {
                if ((blob [offset] != 0x06) ||                                          // PUBLICKEYBLOB (0x06)
                    (blob [offset + 1] != 0x02) ||                                      // Version (0x02)
                    (blob [offset + 2] != 0x00) ||                                      // Reserved (word)
                    (blob [offset + 3] != 0x00) ||
                    (ToUInt32LE(blob, offset + 8) != 0x31535344))                       // DWORD magic
                {
                    throw new CryptographicException("Invalid blob header");
                }

                int           bitlen  = ToInt32LE(blob, offset + 12);
                DSAParameters dsap    = new DSAParameters();
                int           bytelen = bitlen >> 3;
                int           pos     = offset + 16;

                dsap.P = new byte [bytelen];
                Buffer.BlockCopy(blob, pos, dsap.P, 0, bytelen);
                Array.Reverse(dsap.P);
                pos += bytelen;

                dsap.Q = new byte [20];
                Buffer.BlockCopy(blob, pos, dsap.Q, 0, 20);
                Array.Reverse(dsap.Q);
                pos += 20;

                dsap.G = new byte [bytelen];
                Buffer.BlockCopy(blob, pos, dsap.G, 0, bytelen);
                Array.Reverse(dsap.G);
                pos += bytelen;

                dsap.Y = new byte [bytelen];
                Buffer.BlockCopy(blob, pos, dsap.Y, 0, bytelen);
                Array.Reverse(dsap.Y);
                pos += bytelen;

                dsap.Counter = ToInt32LE(blob, pos);
                pos         += 4;

                dsap.Seed = new byte [20];
                Buffer.BlockCopy(blob, pos, dsap.Seed, 0, 20);
                Array.Reverse(dsap.Seed);
                pos += 20;

                DSA dsa = (DSA)DSA.Create();
                dsa.ImportParameters(dsap);
                return(dsa);
            }
            catch (Exception e) {
                throw new CryptographicException("Invalid blob.", e);
            }
        }
Пример #6
0
 public override bool VerifyData(DSA dsa, byte[] data, byte[] signature, HashAlgorithmName hashAlgorithm) =>
 dsa.VerifyData(data, signature, hashAlgorithm);
Пример #7
0
 public override bool VerifyData(DSA dsa, byte[] data, byte[] signature, HashAlgorithmName hashAlgorithm) =>
 dsa.VerifyData(new MemoryStream(data), signature, hashAlgorithm);
Пример #8
0
        public static X509Certificate2 CopyWithPrivateKey(this X509Certificate2 certificate, DSA privateKey)
        {
            if (certificate == null)
            {
                throw new ArgumentNullException(nameof(certificate));
            }
            if (privateKey == null)
            {
                throw new ArgumentNullException(nameof(privateKey));
            }

            throw new NotImplementedException();
        }
Пример #9
0
        public override AsymmetricSignatureDeformatter GetSignatureDeformatter(string algorithm)
        {
            // We support one of the two algoritms, but not both.
            //     XmlDsigDSAUrl = "http://www.w3.org/2000/09/xmldsig#dsa-sha1";
            //     XmlDsigRSASHA1Url = "http://www.w3.org/2000/09/xmldsig#rsa-sha1";

            if (string.IsNullOrEmpty(algorithm))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(algorithm, SR.Format(SR.EmptyOrNullArgumentString, nameof(algorithm)));
            }

            object algorithmObject = CryptoHelper.GetAlgorithmFromConfig(algorithm);

            if (algorithmObject != null)
            {
                SignatureDescription description = algorithmObject as SignatureDescription;
                if (description != null)
                {
                    return(description.CreateDeformatter(PublicKey));
                }

                try
                {
                    AsymmetricSignatureDeformatter asymmetricSignatureDeformatter = algorithmObject as AsymmetricSignatureDeformatter;
                    if (asymmetricSignatureDeformatter != null)
                    {
                        asymmetricSignatureDeformatter.SetKey(PublicKey);
                        return(asymmetricSignatureDeformatter);
                    }
                }
                catch (InvalidCastException e)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.AlgorithmAndPublicKeyMisMatch, e));
                }

                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(SR.Format(SR.UnsupportedAlgorithmForCryptoOperation,
                                                                                                               algorithm, nameof(GetSignatureDeformatter))));
            }

            switch (algorithm)
            {
            case SignedXml.XmlDsigDSAUrl:

                // Ensure that we have a DSA algorithm object.
                DSA dsa = (PublicKey as DSA);
                if (dsa == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException("PublicKeyNotDSA"));
                }

                return(new DSASignatureDeformatter(dsa));

            case SignedXml.XmlDsigRSASHA1Url:
            case SecurityAlgorithms.RsaSha256Signature:
                // Ensure that we have an RSA algorithm object.
                RSA rsa = (PublicKey as RSA);
                if (rsa == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.PublicKeyNotRSA));
                }

                return(new RSAPKCS1SignatureDeformatter(rsa));

            default:
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.UnsupportedCryptoAlgorithm, algorithm)));
            }
        }
Пример #10
0
        private Renci.SshNet.SftpClient _getSFtpClientWithCertificate()
        {
#if NETSTANDARD2_0 || NET472
            throw new NotSupportedException($"ClientCertificate does not support X509 Certificate in NETCORE2.0 nor NET472");
#else
            var connInfo = _getConnectionInfo();

            var cert = FtpConfig.ClientCertificate;

            string keyExchangeAlgorithm = null;
            byte[] privateKeyBytes      = null;
            string privateKeyPemString;
            bool   isKeyNull = false;

            switch (cert.PublicKey.Oid.Value)
            {
            case _rsa:
            {
                using RSA rsaKey = cert.GetRSAPrivateKey();

                keyExchangeAlgorithm = rsaKey.KeyExchangeAlgorithm;
                if (rsaKey != null)
                {
                    privateKeyBytes = rsaKey.ExportRSAPrivateKey();
                }
                else
                {
                    isKeyNull = true;
                }
                break;
            }

            case _dsa:
            {
                using DSA dsaKey = cert.GetDSAPrivateKey();

                keyExchangeAlgorithm = dsaKey.KeyExchangeAlgorithm;
                if (dsaKey != null)
                {
                    privateKeyBytes = dsaKey.ExportPkcs8PrivateKey();
                }
                else
                {
                    isKeyNull = true;
                }
                break;
            }

            case _ecdsa:
            {
                using ECDsa ecdsaKey = cert.GetECDsaPrivateKey();

                keyExchangeAlgorithm = ecdsaKey.KeyExchangeAlgorithm;
                if (ecdsaKey != null)
                {
                    privateKeyBytes = ecdsaKey.ExportPkcs8PrivateKey();
                }
                else
                {
                    isKeyNull = true;
                }
                break;
            }

            default:
                throw new NotSupportedException($"ClientCertificate does not support the given algorithm {cert.PublicKey.Oid.FriendlyName}");
            }

            if (isKeyNull)
            {
                throw new ArgumentNullException($"ClientCertificate has a null Key");
            }

#if NET5_0_OR_GREATER
            var privateKeyPem = PemEncoding.Write($"{keyExchangeAlgorithm} PRIVATE KEY", privateKeyBytes);
            privateKeyPemString = new string(privateKeyPem);
#else
            var builder = new StringBuilder();
            builder.AppendLine($"-----BEGIN {keyExchangeAlgorithm} PRIVATE KEY-----");
            builder.AppendLine(
                Convert.ToBase64String(privateKeyBytes, Base64FormattingOptions.InsertLineBreaks));
            builder.AppendLine($"-----END {keyExchangeAlgorithm} PRIVATE KEY-----");

            privateKeyPemString = builder.ToString();
#endif

            var byteArray = Encoding.UTF8.GetBytes(privateKeyPemString);

            using var ms             = new MemoryStream(byteArray);
            using var privateKeyFile = new PrivateKeyFile(ms);

            return(new Renci.SshNet.SftpClient(connInfo.Host, connInfo.Username, new PrivateKeyFile[] { privateKeyFile })
            {
                KeepAliveInterval = _keepAliveInterval,
                OperationTimeout = _operationTimeout,
            });
#endif
        }
 public void FixtureSetUp()
 {
     // key generation is VERY long so one time is enough
     dsa = DSA.Create();
     rsa = RSA.Create();
 }
Пример #12
0
        public static void hogehoge(string[] args)
        {
            try
            {
                #region Variables

                #region Env

                // https://github.com/dotnet/corefx/issues/29404#issuecomment-385287947
                //   *.pfxから証明書を開く場合、X509KeyStorageFlags.Exportableの指定が必要な場合がある。
                //   Linuxのキーは常にエクスポート可能だが、WindowsやMacOSでは必ずしもそうではない。
                X509KeyStorageFlags x509KSF = 0;
                x509KSF = X509KeyStorageFlags.DefaultKeySet;
                #endregion

                #region Token
                string token = "";
                IDictionary <string, object> headers = null;
                IDictionary <string, object> payload = null;
                payload = new Dictionary <string, object>()
                {
                    { "sub", "*****@*****.**" },
                    { "exp", 1300819380 }
                };
                #endregion

                #region Keys
                string jwk = "";

                byte[] secretKey = null;
                byte[] x         = null;
                byte[] y         = null;
                byte[] d         = null;

                string           privateX509Path = "";
                string           publicX509Path  = "";
                X509Certificate2 publicX509Key   = null;
                X509Certificate2 privateX509Key  = null;

                RSA rsa = null;
                //DSA dsa = null;

                CngKey publicKeyOfCng = null;
                //CngKey privateKeyOfCng = null;
                ECParameters eCParameters = new ECParameters();
                #endregion

                #region DigitalSign
                byte[] data = CustomEncode.StringToByte("hogehoge", CustomEncode.UTF_8);
                byte[] sign = null;
                #endregion

                #endregion

                #region Test of the X.509 Certificates

                #region RSA
                privateX509Path = @"SHA256RSA.pfx";
                publicX509Path  = @"SHA256RSA.cer";
                privateX509Key  = new X509Certificate2(privateX509Path, "test", x509KSF);
                publicX509Key   = new X509Certificate2(publicX509Path, "", x509KSF);
                WriteLine.InspectPrivateX509Key("RSA", privateX509Key);
                WriteLine.InspectPublicX509Key("RSA", publicX509Key);
                #endregion

                #region DSA
                // https://github.com/dotnet/corefx/issues/18733#issuecomment-296723615
                privateX509Path = @"SHA256DSA.pfx";
                publicX509Path  = @"SHA256DSA.cer";
                privateX509Key  = new X509Certificate2(privateX509Path, "test");
                publicX509Key   = new X509Certificate2(publicX509Path, "");
                WriteLine.InspectPrivateX509Key("DSA", privateX509Key);
                WriteLine.InspectPublicX509Key("DSA", publicX509Key);
                DSA privateDSA = privateX509Key.GetDSAPrivateKey();
                WriteLine.OutPutDebugAndConsole("privateDSA",
                                                (privateDSA == null ? "is null" : "is not null"));
                //DSA publicDSA = null; // publicX509Key.GetDSAPublicKey(); // Internal.Cryptography.CryptoThrowHelper.WindowsCryptographicException
                #endregion

                #region ECDsa
                // https://github.com/dotnet/corefx/issues/18733#issuecomment-296723615
                privateX509Path = @"SHA256ECDSA.pfx";
                publicX509Path  = @"SHA256ECDSA.cer";
                privateX509Key  = new X509Certificate2(privateX509Path, "test");
                publicX509Key   = new X509Certificate2(publicX509Path, "");
                WriteLine.InspectPrivateX509Key("ECDsa", privateX509Key);
                WriteLine.InspectPublicX509Key("ECDsa", publicX509Key);

                ECDsa privateECDsa = privateX509Key.GetECDsaPrivateKey();
                WriteLine.OutPutDebugAndConsole("privateECDsa",
                                                (privateECDsa == null ? "is null" : "is not null"));

                ECDsa publicECDsa = publicX509Key.GetECDsaPublicKey();
                WriteLine.OutPutDebugAndConsole("publicECDsa",
                                                (publicECDsa == null ? "is null" : "is not null"));
                #endregion

                #endregion

                WriteLine.OutPutDebugAndConsole("----------------------------------------------------------------------------------------------------");

                #region Test of the OpenTouryo.Public.Security.

                DigitalSignParam dsParam = null;
                DigitalSignXML   dsXML   = null;
                DigitalSignX509  dsX509  = null;

                #region RSA
                dsParam = new DigitalSignParam(EnumDigitalSignAlgorithm.RsaOpenSsl_SHA256);
                sign    = dsParam.Sign(data);
                WriteLine.OutPutDebugAndConsole("DigitalSignParam.Verify(RS256)",
                                                dsParam.Verify(data, sign).ToString());

                dsXML = new DigitalSignXML(EnumDigitalSignAlgorithm.RsaOpenSsl_SHA256);
                sign  = dsXML.Sign(data);
                WriteLine.OutPutDebugAndConsole("DigitalSignXML.Verify(RS256)",
                                                dsXML.Verify(data, sign).ToString());

                dsX509 = new DigitalSignX509(@"SHA256RSA.pfx", "test", "SHA256");
                sign   = dsX509.Sign(data);
                WriteLine.OutPutDebugAndConsole("DigitalSignX509.Verify(RSA)",
                                                dsX509.Verify(data, sign).ToString());

                // 鍵の相互変換
                jwk = RsaPublicKeyConverter.ParamToJwk(
                    ((RSA)dsX509.AsymmetricAlgorithm).ExportParameters(false));

                WriteLine.OutPutDebugAndConsole("RSA JWK", jwk);

                dsParam = new DigitalSignParam(
                    RsaPublicKeyConverter.JwkToParam(jwk),
                    EnumDigitalSignAlgorithm.RsaCSP_SHA256);

                WriteLine.OutPutDebugAndConsole("DigitalSignX509.Verify(RSA JWK)",
                                                dsParam.Verify(data, sign).ToString());
                #endregion

                #region DSA
                dsParam = new DigitalSignParam(EnumDigitalSignAlgorithm.DsaOpenSsl_SHA1);
                sign    = dsParam.Sign(data);
                WriteLine.OutPutDebugAndConsole(
                    "DigitalSignParam.Verify(DS1)",
                    dsParam.Verify(data, sign).ToString());

                dsXML = new DigitalSignXML(EnumDigitalSignAlgorithm.DsaOpenSsl_SHA1);
                sign  = dsXML.Sign(data);
                WriteLine.OutPutDebugAndConsole(
                    "DigitalSignXML.Verify(DS1)",
                    dsXML.Verify(data, sign).ToString());

                dsX509 = new DigitalSignX509(@"SHA256DSA.pfx", "test", "SHA256");
                sign   = dsX509.Sign(data);
                WriteLine.OutPutDebugAndConsole(
                    "DigitalSignX509.Verify(DSA)",
                    dsX509.Verify(data, sign).ToString());
                #endregion

                #region ECDSA
                // .NET Core on Linux
                DigitalSignECDsaX509 ecDsX509 = new DigitalSignECDsaX509(
                    @"SHA256ECDSA.pfx", "test", HashAlgorithmName.SHA256);

                sign = ecDsX509.Sign(data);
                WriteLine.OutPutDebugAndConsole(
                    "DigitalSignX509.Verify(ECDSA)",
                    ecDsX509.Verify(data, sign).ToString());

                token = "";
                token = JWT.Encode(payload, ((ECDsa)ecDsX509.AsymmetricAlgorithm), JwsAlgorithm.ES256);

                // 鍵の相互変換
                jwk = EccPublicKeyConverter.ParamToJwk(
                    ((ECDsa)ecDsX509.AsymmetricAlgorithm).ExportParameters(false));

                WriteLine.OutPutDebugAndConsole("ECDSA JWK", jwk);

                DigitalSignECDsaOpenSsl ecDsParam =
                    new DigitalSignECDsaOpenSsl(
                        EccPublicKeyConverter.JwkToParam(jwk),
                        HashAlgorithmCmnFunc.GetHashAlgorithmFromNameString(HashNameConst.SHA256));

                WriteLine.OutPutDebugAndConsole(
                    "DigitalSignX509.Verify(ECDSA JWK)",
                    ecDsParam.Verify(data, sign).ToString());

                Program.VerifyResult("JwsAlgorithm.ES256", token, ecDsParam.AsymmetricAlgorithm);

                #endregion

                #endregion

                WriteLine.OutPutDebugAndConsole("----------------------------------------------------------------------------------------------------");

                #region Test of the jose-jwt

                #region JWT

                #region Unsecured JWT
                // Creating Plaintext (unprotected) Tokens
                // https://github.com/dvsekhvalnov/jose-jwt#creating-plaintext-unprotected-tokens
                token = "";
                token = JWT.Encode(payload, null, JwsAlgorithm.none);
                WriteLine.OutPutDebugAndConsole("JwsAlgorithm.none", token);
                #endregion

                #region JWS (Creating signed Tokens)
                // https://github.com/dvsekhvalnov/jose-jwt#creating-signed-tokens

                #region HS-* family
                // HS256, HS384, HS512
                // https://github.com/dvsekhvalnov/jose-jwt#hs--family
                secretKey = new byte[] { 164, 60, 194, 0, 161, 189, 41, 38, 130, 89, 141, 164, 45, 170, 159, 209, 69, 137, 243, 216, 191, 131, 47, 250, 32, 107, 231, 117, 37, 158, 225, 234 };
                token     = "";
                token     = JWT.Encode(payload, secretKey, JwsAlgorithm.HS256);
                Program.VerifyResult("JwsAlgorithm.HS256", token, secretKey);
                #endregion

                #region RS-* and PS-* family
                // RS256, RS384, RS512 and PS256, PS384, PS512
                // https://github.com/dvsekhvalnov/jose-jwt#rs--and-ps--family
                // X509Certificate2 x509Certificate2 = new X509Certificate2();

                privateX509Path = @"SHA256RSA.pfx";
                publicX509Path  = @"SHA256RSA.cer";
                privateX509Key  = new X509Certificate2(privateX509Path, "test", x509KSF);
                publicX509Key   = new X509Certificate2(publicX509Path, "", x509KSF);

                token = "";

                rsa   = (RSA)privateX509Key.PrivateKey;
                token = JWT.Encode(payload, rsa, JwsAlgorithm.RS256);
                Program.VerifyResult("JwsAlgorithm.RS256", token, rsa);

                #endregion

                #region ES- * family
                // ES256, ES384, ES512 ECDSA signatures
                // https://github.com/dvsekhvalnov/jose-jwt#es---family

                x = new byte[] { 4, 114, 29, 223, 58, 3, 191, 170, 67, 128, 229, 33, 242, 178, 157, 150, 133, 25, 209, 139, 166, 69, 55, 26, 84, 48, 169, 165, 67, 232, 98, 9 };
                y = new byte[] { 131, 116, 8, 14, 22, 150, 18, 75, 24, 181, 159, 78, 90, 51, 71, 159, 214, 186, 250, 47, 207, 246, 142, 127, 54, 183, 72, 72, 253, 21, 88, 53 };
                d = new byte[] { 42, 148, 231, 48, 225, 196, 166, 201, 23, 190, 229, 199, 20, 39, 226, 70, 209, 148, 29, 70, 125, 14, 174, 66, 9, 198, 80, 251, 95, 107, 98, 206 };

                eCParameters = new ECParameters();

                // Curve
                eCParameters.Curve =
                    EccPublicKeyConverter.GetECCurveFromCrvString(
                        EccPublicKeyConverter.GetCrvStringFromXCoordinate(x));

                // x, y, d
                eCParameters.Q.X = x;
                eCParameters.Q.Y = y;
                eCParameters.D   = d;
                ECDsaOpenSsl eCDsaOpenSsl = new ECDsaOpenSsl(eCParameters.Curve);
                eCDsaOpenSsl.ImportParameters(eCParameters);

                token = "";
                token = JWT.Encode(payload, eCDsaOpenSsl, JwsAlgorithm.ES256);
                Program.VerifyResult("JwsAlgorithm.ES256", token, eCDsaOpenSsl);

                try
                {
                    privateX509Path = @"SHA256ECDSA.pfx";
                    publicX509Path  = @"SHA256ECDSA.cer";
                    privateX509Key  = new X509Certificate2(privateX509Path, "test");
                    publicX509Key   = new X509Certificate2(publicX509Path, "");

                    // ECCurveを分析してみる。
                    ECCurve eCCurve = ((ECDsaOpenSsl)privateX509Key.GetECDsaPrivateKey()).ExportExplicitParameters(true).Curve;
                    WriteLine.OutPutDebugAndConsole("Inspect ECCurve", ObjectInspector.Inspect(eCCurve));

                    token = "";
                    token = JWT.Encode(payload, privateX509Key.GetECDsaPrivateKey(), JwsAlgorithm.ES256);
                    Program.VerifyResult("JwsAlgorithm.ES256", token, publicX509Key.GetECDsaPublicKey());
                }
                catch (Exception ex)
                {
                    WriteLine.OutPutDebugAndConsole("JwsAlgorithm.ES256", ex.GetType().ToString() + ", " + ex.Message);
                }

                #endregion

                #endregion

                #region JWE (Creating encrypted Tokens)
                // https://github.com/dvsekhvalnov/jose-jwt#creating-encrypted-tokens

                #region RSA-* key management family of algorithms
                // RSA-OAEP-256, RSA-OAEP and RSA1_5 key
                // https://github.com/dvsekhvalnov/jose-jwt#rsa--key-management-family-of-algorithms

                privateX509Path = @"SHA256RSA.pfx";
                publicX509Path  = @"SHA256RSA.cer";
                privateX509Key  = new X509Certificate2(privateX509Path, "test", x509KSF);
                publicX509Key   = new X509Certificate2(publicX509Path, "", x509KSF);

                // RSAES-PKCS1-v1_5 and AES_128_CBC_HMAC_SHA_256
                token = "";
                token = JWT.Encode(payload, publicX509Key.PublicKey.Key, JweAlgorithm.RSA1_5, JweEncryption.A128CBC_HS256);
                Program.VerifyResult("JweAlgorithm.RSA1_5, JweEncryption.A128CBC_HS256", token, privateX509Key.PrivateKey);

                // RSAES-OAEP and AES GCM
                try
                {
                    token = "";
                    token = JWT.Encode(payload, publicX509Key.PublicKey.Key, JweAlgorithm.RSA_OAEP, JweEncryption.A256GCM);
                    Program.VerifyResult("JweAlgorithm.RSA_OAEP, JweEncryption.A256GCM", token, privateX509Key.PrivateKey);
                }
                catch (Exception ex)
                {
                    // Unhandled Exception: System.DllNotFoundException: Unable to load DLL 'bcrypt.dll' at ubunntu
                    WriteLine.OutPutDebugAndConsole("JweAlgorithm.RSA_OAEP, JweEncryption.A256GCM", ex.GetType().ToString() + ", " + ex.Message);
                }
                #endregion

                #region Other key management family of algorithms

                secretKey = new byte[] { 164, 60, 194, 0, 161, 189, 41, 38, 130, 89, 141, 164, 45, 170, 159, 209, 69, 137, 243, 216, 191, 131, 47, 250, 32, 107, 231, 117, 37, 158, 225, 234 };

                #region DIR direct pre-shared symmetric key family of algorithms
                // https://github.com/dvsekhvalnov/jose-jwt#dir-direct-pre-shared-symmetric-key-family-of-algorithms
                token = "";
                token = JWT.Encode(payload, secretKey, JweAlgorithm.DIR, JweEncryption.A128CBC_HS256);
                Program.VerifyResult("JweAlgorithm.DIR, JweEncryption.A128CBC_HS256", token, secretKey);
                #endregion

                #region AES Key Wrap key management family of algorithms
                // AES128KW, AES192KW and AES256KW key management
                // https://github.com/dvsekhvalnov/jose-jwt#aes-key-wrap-key-management-family-of-algorithms
                token = "";
                token = JWT.Encode(payload, secretKey, JweAlgorithm.A256KW, JweEncryption.A256CBC_HS512);
                Program.VerifyResult("JweAlgorithm.A256KW, JweEncryption.A256CBC_HS512", token, secretKey);
                #endregion

                #region AES GCM Key Wrap key management family of algorithms
                // AES128GCMKW, AES192GCMKW and AES256GCMKW key management
                // https://github.com/dvsekhvalnov/jose-jwt#aes-gcm-key-wrap-key-management-family-of-algorithms
                try
                {
                    token = "";
                    token = JWT.Encode(payload, secretKey, JweAlgorithm.A256GCMKW, JweEncryption.A256CBC_HS512);
                    Program.VerifyResult("JweAlgorithm.A256GCMKW, JweEncryption.A256CBC_HS512", token, secretKey);
                }
                catch (Exception ex)
                {
                    // Unhandled Exception: System.DllNotFoundException: Unable to load DLL 'bcrypt.dll' at ubunntu
                    WriteLine.OutPutDebugAndConsole("JweAlgorithm.A256GCMKW, JweEncryption.A256CBC_HS512", ex.GetType().ToString() + ", " + ex.Message);
                }
                #endregion

                #region ECDH-ES and ECDH-ES with AES Key Wrap key management family of algorithms
                // ECDH-ES and ECDH-ES+A128KW, ECDH-ES+A192KW, ECDH-ES+A256KW key management
                // https://github.com/dvsekhvalnov/jose-jwt#ecdh-es-and-ecdh-es-with-aes-key-wrap-key-management-family-of-algorithms
                try
                {
                    x = new byte[] { 4, 114, 29, 223, 58, 3, 191, 170, 67, 128, 229, 33, 242, 178, 157, 150, 133, 25, 209, 139, 166, 69, 55, 26, 84, 48, 169, 165, 67, 232, 98, 9 };
                    y = new byte[] { 131, 116, 8, 14, 22, 150, 18, 75, 24, 181, 159, 78, 90, 51, 71, 159, 214, 186, 250, 47, 207, 246, 142, 127, 54, 183, 72, 72, 253, 21, 88, 53 };
                    publicKeyOfCng = EccKey.New(x, y, usage: CngKeyUsages.KeyAgreement);
                    token          = "";
                    token          = JWT.Encode(payload, publicKeyOfCng, JweAlgorithm.ECDH_ES, JweEncryption.A256GCM);
                    Program.VerifyResult("JweAlgorithm.ECDH_ES, JweEncryption.A256GCM", token, publicKeyOfCng);
                }
                catch (Exception ex)
                {
                    // System.NotImplementedException: 'not yet'
                    WriteLine.OutPutDebugAndConsole("JweAlgorithm.ECDH_ES, JweEncryption.A256GCM", ex.GetType().ToString() + ", " + ex.Message);
                }
                #endregion

                #region PBES2 using HMAC SHA with AES Key Wrap key management family of algorithms
                token = "";
                token = JWT.Encode(payload, "top secret", JweAlgorithm.PBES2_HS256_A128KW, JweEncryption.A256CBC_HS512);
                Program.VerifyResult("JweAlgorithm.PBES2_HS256_A128KW, JweEncryption.A256CBC_HS512", token, "top secret");
                #endregion

                #endregion

                #endregion

                #endregion

                #endregion
            }
            catch (Exception ex)
            {
                WriteLine.OutPutDebugAndConsole(ex.ToString());
            }
        }
Пример #13
0
 public static byte[] Encode(DSA dsa)
 {
     return(ASN1Convert.FromUnsignedBigInteger(dsa.ExportParameters(true).X).GetBytes());
 }
Пример #14
0
		private static Authority MakeRoot()
		{
			DSA dsa = new DSA(new DSAParameters(512));
			CryptoKey key = new CryptoKey(dsa);
			X509Name subject = new X509Name("CN=.");
			X509Certificate cert = new X509Certificate(
				0,
				subject,
				subject,
				key,
				TimeSpan.FromDays(365));
			cert.Sign(key, MessageDigest.DSS1);

			return new Authority(cert, key);
		}
Пример #15
0
        //
        // public constructors
        //

        public DSAKeyValue()
        {
            _key = DSA.Create();
        }
Пример #16
0
        public override AsymmetricSignatureFormatter GetSignatureFormatter(string algorithm)
        {
            // One can sign only if the private key is present.
            if (PrivateKey == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.NoPrivateKeyAvailable));
            }

            if (string.IsNullOrEmpty(algorithm))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(algorithm, SR.Format(SR.EmptyOrNullArgumentString, nameof(algorithm)));
            }

            // We support:
            //     XmlDsigDSAUrl = "http://www.w3.org/2000/09/xmldsig#dsa-sha1";
            //     XmlDsigRSASHA1Url = "http://www.w3.org/2000/09/xmldsig#rsa-sha1";
            //     RsaSha256Signature = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
            AsymmetricAlgorithm privateKey = PrivateKey;

            object algorithmObject = CryptoHelper.GetAlgorithmFromConfig(algorithm);

            if (algorithmObject != null)
            {
                SignatureDescription description = algorithmObject as SignatureDescription;
                if (description != null)
                {
                    return(description.CreateFormatter(privateKey));
                }

                try
                {
                    AsymmetricSignatureFormatter asymmetricSignatureFormatter = algorithmObject as AsymmetricSignatureFormatter;
                    if (asymmetricSignatureFormatter != null)
                    {
                        asymmetricSignatureFormatter.SetKey(privateKey);
                        return(asymmetricSignatureFormatter);
                    }
                }
                catch (InvalidCastException e)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.AlgorithmAndPrivateKeyMisMatch, e));
                }

                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CryptographicException(SR.Format(SR.UnsupportedAlgorithmForCryptoOperation,
                                                                                                               algorithm, nameof(GetSignatureFormatter))));
            }

            switch (algorithm)
            {
            case SignedXml.XmlDsigDSAUrl:

                // Ensure that we have a DSA algorithm object.
                DSA dsa = (PrivateKey as DSA);
                if (dsa == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.PrivateKeyNotDSA));
                }
                return(new DSASignatureFormatter(dsa));

            case SignedXml.XmlDsigRSASHA1Url:
                // Ensure that we have an RSA algorithm object.
                RSA rsa = (PrivateKey as RSA);
                if (rsa == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.PrivateKeyNotRSA));
                }

                return(new RSAPKCS1SignatureFormatter(rsa));

            case SecurityAlgorithms.RsaSha256Signature:
                // Ensure that we have an RSA algorithm object.
                RSA rsaSha256 = (privateKey as RSA);
                if (rsaSha256 == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.PrivateKeyNotRSA));
                }

                return(new RSAPKCS1SignatureFormatter(rsaSha256));

            default:
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.UnsupportedCryptoAlgorithm, algorithm)));
            }
        }
Пример #17
0
		public Authority(string name)
		{
			DSA dsa = new DSA(new DSAParameters(512));
			this.key = new CryptoKey(dsa);
			this.name = name;
		}
Пример #18
0
 public DSAKeyValue(DSA key)
 {
     _key = key;
 }
Пример #19
0
 public override byte[] SignData(DSA dsa, byte[] data, HashAlgorithmName hashAlgorithm) =>
 dsa.SignData(new MemoryStream(data), hashAlgorithm);
Пример #20
0
 public DSAKeyValue()
 {
     dsa = (DSA)DSA.Create();
 }
Пример #21
0
 public override byte[] SignData(DSA dsa, byte[] data, HashAlgorithmName hashAlgorithm) =>
 TryWithOutputArray(dest => dsa.TrySignData(data, dest, hashAlgorithm, out int bytesWritten) ? (true, bytesWritten) : (false, 0));
Пример #22
0
 public DSAKeyValue(DSA key)
 {
     dsa = key;
 }
Пример #23
0
        static public DSA FromCapiPrivateKeyBlobDSA(byte[] blob, int offset)
        {
            if (blob == null)
            {
                throw new ArgumentNullException("blob");
            }
            if (offset >= blob.Length)
            {
                throw new ArgumentException("blob is too small.");
            }

            DSAParameters dsap = new DSAParameters();

            try {
                if ((blob [offset] != 0x07) ||                                          // PRIVATEKEYBLOB (0x07)
                    (blob [offset + 1] != 0x02) ||                                      // Version (0x02)
                    (blob [offset + 2] != 0x00) ||                                      // Reserved (word)
                    (blob [offset + 3] != 0x00) ||
                    (ToUInt32LE(blob, offset + 8) != 0x32535344))                       // DWORD magic
                {
                    throw new CryptographicException("Invalid blob header");
                }

                int bitlen  = ToInt32LE(blob, offset + 12);
                int bytelen = bitlen >> 3;
                int pos     = offset + 16;

                dsap.P = new byte [bytelen];
                Buffer.BlockCopy(blob, pos, dsap.P, 0, bytelen);
                Array.Reverse(dsap.P);
                pos += bytelen;

                dsap.Q = new byte [20];
                Buffer.BlockCopy(blob, pos, dsap.Q, 0, 20);
                Array.Reverse(dsap.Q);
                pos += 20;

                dsap.G = new byte [bytelen];
                Buffer.BlockCopy(blob, pos, dsap.G, 0, bytelen);
                Array.Reverse(dsap.G);
                pos += bytelen;

                dsap.X = new byte [20];
                Buffer.BlockCopy(blob, pos, dsap.X, 0, 20);
                Array.Reverse(dsap.X);
                pos += 20;

                dsap.Counter = ToInt32LE(blob, pos);
                pos         += 4;

                dsap.Seed = new byte [20];
                Buffer.BlockCopy(blob, pos, dsap.Seed, 0, 20);
                Array.Reverse(dsap.Seed);
                pos += 20;
            }
            catch (Exception e) {
                throw new CryptographicException("Invalid blob.", e);
            }

#if INSIDE_CORLIB && MOBILE
            DSA dsa = (DSA)DSA.Create();
            dsa.ImportParameters(dsap);
#else
            DSA dsa = null;
            try {
                dsa = (DSA)DSA.Create();
                dsa.ImportParameters(dsap);
            }
            catch (CryptographicException ce) {
                // this may cause problem when this code is run under
                // the SYSTEM identity on Windows (e.g. ASP.NET). See
                // http://bugzilla.ximian.com/show_bug.cgi?id=77559
                try {
                    CspParameters csp = new CspParameters();
                    csp.Flags = CspProviderFlags.UseMachineKeyStore;
                    dsa       = new DSACryptoServiceProvider(csp);
                    dsa.ImportParameters(dsap);
                }
                catch {
                    // rethrow original, not the later, exception if this fails
                    throw ce;
                }
            }
#endif
            return(dsa);
        }
Пример #24
0
        public static ClaimsIdentity CreateFromCertificate(X509Certificate2 certificate, string authenticationType = "X.509", bool includeAllClaims = false)
        {
            var claims = new List <Claim>();
            var issuer = certificate.Issuer;

            claims.Add(new Claim("issuer", issuer));

            var thumbprint = certificate.Thumbprint;

            claims.Add(new Claim(ClaimTypes.Thumbprint, thumbprint, ClaimValueTypes.Base64Binary, issuer));

            string name = certificate.SubjectName.Name;

            if (!string.IsNullOrEmpty(name))
            {
                claims.Add(new Claim(ClaimTypes.X500DistinguishedName, name, ClaimValueTypes.String, issuer));
            }

            if (includeAllClaims)
            {
                name = certificate.SerialNumber;
                if (!string.IsNullOrEmpty(name))
                {
                    claims.Add(new Claim(ClaimTypes.SerialNumber, name, "http://www.w3.org/2001/XMLSchema#string", issuer));
                }

                name = certificate.GetNameInfo(X509NameType.DnsName, false);
                if (!string.IsNullOrEmpty(name))
                {
                    claims.Add(new Claim(ClaimTypes.Dns, name, ClaimValueTypes.String, issuer));
                }

                name = certificate.GetNameInfo(X509NameType.SimpleName, false);
                if (!string.IsNullOrEmpty(name))
                {
                    claims.Add(new Claim(ClaimTypes.Name, name, ClaimValueTypes.String, issuer));
                }

                name = certificate.GetNameInfo(X509NameType.EmailName, false);
                if (!string.IsNullOrEmpty(name))
                {
                    claims.Add(new Claim(ClaimTypes.Email, name, ClaimValueTypes.String, issuer));
                }

                name = certificate.GetNameInfo(X509NameType.UpnName, false);
                if (!string.IsNullOrEmpty(name))
                {
                    claims.Add(new Claim(ClaimTypes.Upn, name, ClaimValueTypes.String, issuer));
                }

                name = certificate.GetNameInfo(X509NameType.UrlName, false);
                if (!string.IsNullOrEmpty(name))
                {
                    claims.Add(new Claim(ClaimTypes.Uri, name, ClaimValueTypes.String, issuer));
                }

                RSA key = certificate.PublicKey.Key as RSA;
                if (key != null)
                {
                    claims.Add(new Claim(ClaimTypes.Rsa, key.ToXmlString(false), ClaimValueTypes.RsaKeyValue, issuer));
                }

                DSA dsa = certificate.PublicKey.Key as DSA;
                if (dsa != null)
                {
                    claims.Add(new Claim(ClaimTypes.Dsa, dsa.ToXmlString(false), ClaimValueTypes.DsaKeyValue, issuer));
                }

                var expiration = certificate.GetExpirationDateString();
                if (!string.IsNullOrEmpty(expiration))
                {
                    claims.Add(new Claim(ClaimTypes.Expiration, expiration, ClaimValueTypes.DateTime, issuer));
                }
            }

            return(new ClaimsIdentity(claims, authenticationType));
        }
Пример #25
0
 public DSA Create()
 {
     return(DSA.Create());
 }
Пример #26
0
 /// <summary>
 /// Adds an enveloped digital signature of type DSA-SHA1 to the eData content and
 /// saves it to a new file.
 /// </summary>
 /// <param name="key"></param>
 /// <param name="saveFile"></param>
 public void Sign(DSA key, string saveFile)
 {
     Sign(null, key, saveFile);
 }
Пример #27
0
            static public byte[] Encode(DSA dsa)
            {
                DSAParameters param = dsa.ExportParameters(true);

                return(ASN1Convert.FromUnsignedBigInteger(param.X).GetBytes());
            }
Пример #28
0
 public abstract byte[] SignData(DSA dsa, byte[] data, HashAlgorithmName hashAlgorithm);
Пример #29
0
 public static void CreateWithKeysize_InvalidKeySize(int keySizeInBits)
 {
     Assert.Throws <CryptographicException>(() => DSA.Create(keySizeInBits));
 }
Пример #30
0
 public abstract bool VerifyData(DSA dsa, byte[] data, byte[] signature, HashAlgorithmName hashAlgorithm);
Пример #31
0
 public static DsaPublicKeyParameters GetDsaPublicKey(DSA dsa)
 {
     return(GetDsaPublicKey(dsa.ExportParameters(false)));
 }
Пример #32
0
 public override byte[] SignData(DSA dsa, byte[] data, HashAlgorithmName hashAlgorithm) =>
 dsa.SignData(data, hashAlgorithm);
        private static void VerifyKey_DSA(DSA dsa)
        {
            DSAParameters dsaParameters = dsa.ExportParameters(false);

            byte[] expected_g = (
                "859B5AEB351CF8AD3FABAC22AE0350148FD1D55128472691709EC08481584413" +
                "E9E5E2F61345043B05D3519D88C021582CCEF808AF8F4B15BD901A310FEFD518" +
                "AF90ABA6F85F6563DB47AE214A84D0B7740C9394AA8E3C7BFEF1BEEDD0DAFDA0" +
                "79BF75B2AE4EDB7480C18B9CDFA22E68A06C0685785F5CFB09C2B80B1D05431D").HexToByteArray();
            byte[] expected_p = (
                "871018CC42552D14A5A9286AF283F3CFBA959B8835EC2180511D0DCEB8B97928" +
                "5708C800FC10CB15337A4AC1A48ED31394072015A7A6B525986B49E5E1139737" +
                "A794833C1AA1E0EAAA7E9D4EFEB1E37A65DBC79F51269BA41E8F0763AA613E29" +
                "C81C3B977AEEB3D3C3F6FEB25C270CDCB6AEE8CD205928DFB33C44D2F2DBE819").HexToByteArray();
            byte[] expected_q = "E241EDCF37C1C0E20AADB7B4E8FF7AA8FDE4E75D".HexToByteArray();
            byte[] expected_y = (
                "089A43F439B924BEF3529D8D6206D1FCA56A55CAF52B41D6CE371EBF07BDA132" +
                "C8EADC040007FCF4DA06C1F30504EBD8A77D301F5A4702F01F0D2A0707AC1DA3" +
                "8DD3251883286E12456234DA62EDA0DF5FE2FA07CD5B16F3638BECCA7786312D" +
                "A7D3594A4BB14E353884DA0E9AECB86E3C9BDB66FCA78EA85E1CC3F2F8BF0963").HexToByteArray();

            Assert.Equal(expected_g, dsaParameters.G);
            Assert.Equal(expected_p, dsaParameters.P);
            Assert.Equal(expected_q, dsaParameters.Q);
            Assert.Equal(expected_y, dsaParameters.Y);
        }
Пример #34
0
		static void Main(string[] args)
		{
			Authorities();
			return;

			SimpleSerialNumber seq = new SimpleSerialNumber();
			X509CertificateAuthority ca = X509CertificateAuthority.SelfSigned(
				seq,
				new X509Name("CN=."),
				TimeSpan.FromDays(10)
			);

			Console.WriteLine(ca.Certificate);

			DSA dsa = new DSA(new DSAParameters(512));
			CryptoKey key = new CryptoKey(dsa);
			X509Request req = new X509Request(0, new X509Name("CN=com."), key);
			req.Sign(key, MessageDigest.DSS1);

			X509Certificate cert = ca.ProcessRequest(req, TimeSpan.FromDays(10));
			Console.WriteLine(cert);
			Console.WriteLine("CA Verified: " + cert.Verify(ca.Key));
			Console.WriteLine("Self Verified: " + cert.Verify(key));

			SimpleSerialNumber serial2 = new SimpleSerialNumber();
			X509CertificateAuthority caSelf = new X509CertificateAuthority(
				cert,
				key,
				serial2);

			X509Request req2 = cert.CreateRequest(key, MessageDigest.DSS1);
			X509Name subject = req2.Subject;
			Console.WriteLine("Request1: " + req);
			Console.WriteLine("Request2: " + req2);

			X509Certificate cert2 = caSelf.ProcessRequest(req2, TimeSpan.FromDays(10));
			Console.WriteLine("Cert2: " + cert2);

			DH dh = new DH(128, 5);

			MessageDigestContext mdc = new MessageDigestContext(MessageDigest.DSS1);
			byte[] msg = dh.PublicKey;
			byte[] sig = mdc.Sign(msg, key);

			Console.WriteLine(dh);
			Console.WriteLine("DH P         : " + BitConverter.ToString(dh.P));
			Console.WriteLine("DH G         : " + BitConverter.ToString(dh.G));
			Console.WriteLine("DH Secret Key: " + BitConverter.ToString(dh.PrivateKey));
			Console.WriteLine("DH Public Key: " + BitConverter.ToString(msg));
			Console.WriteLine("DH Signature : " + BitConverter.ToString(sig));

			Console.WriteLine(mdc.Verify(msg, sig, key));
		}