Beispiel #1
0
        public void TestU2fAttCertNotP256()
        {
            using (var ecdsaAtt = ECDsa.Create(ECCurve.NamedCurves.nistP384))
            {
                var attRequest = new CertificateRequest("CN=U2FTesting, OU=Authenticator Attestation, O=FIDO2-NET-LIB, C=US", ecdsaAtt, HashAlgorithmName.SHA256);

                attRequest.CertificateExtensions.Add(
                    new X509BasicConstraintsExtension(false, false, 0, false));

                using (var attestnCert = attRequest.CreateSelfSigned(DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddDays(2)))
                {
                    var attnStmt = (CborMap)_attestationObject["attStmt"];
                    attnStmt.Set("x5c", new CborArray {
                        attestnCert.RawData
                    });
                }
            }

            var ex = Assert.ThrowsAsync <Fido2VerificationException>(() => MakeAttestationResponse());

            Assert.Equal("Attestation certificate public key is not an Elliptic Curve (EC) public key over the P-256 curve", ex.Result.Message);
        }
Beispiel #2
0
        public virtual void HandleMcpeServerToClientHandshake(McpeServerToClientHandshake message)
        {
            string token = message.token;

            Log.Debug($"JWT:\n{token}");

            IDictionary <string, dynamic> headers = JWT.Headers(token);
            string x5u = headers["x5u"];

            Log.Debug($"JWT payload:\n{JWT.Payload(token)}");

            ECPublicKeyParameters remotePublicKey = (ECPublicKeyParameters)PublicKeyFactory.CreateKey(x5u.DecodeBase64());

            var signParam = new ECParameters
            {
                Curve = ECCurve.NamedCurves.nistP384,
                Q     =
                {
                    X = remotePublicKey.Q.AffineXCoord.GetEncoded(),
                    Y = remotePublicKey.Q.AffineYCoord.GetEncoded()
                },
            };

            signParam.Validate();

            var signKey = ECDsa.Create(signParam);

            try
            {
                var data = JWT.Decode <HandshakeData>(token, signKey);

                Client.InitiateEncryption(Base64Url.Decode(x5u), Base64Url.Decode(data.salt));
            }
            catch (Exception e)
            {
                Log.Error(token, e);
                throw;
            }
        }
Beispiel #3
0
        public static void ECDSA_Signing_RSAPublicKey()
        {
            using (RSA rsa = RSA.Create())
                using (ECDsa ecdsa = ECDsa.Create())
                {
                    var request = new CertificateRequest(
                        new X500DistinguishedName("CN=Test"),
                        ecdsa,
                        HashAlgorithmName.SHA256);

                    request.CertificateExtensions.Add(
                        new X509BasicConstraintsExtension(true, false, 0, true));

                    DateTimeOffset now = DateTimeOffset.UtcNow;

                    using (X509Certificate2 cert = request.CreateSelfSigned(now, now.AddDays(1)))
                    {
                        X509SignatureGenerator rsaGenerator =
                            X509SignatureGenerator.CreateForRSA(rsa, RSASignaturePadding.Pkcs1);

                        request = new CertificateRequest(
                            new X500DistinguishedName("CN=Leaf"),
                            rsaGenerator.PublicKey,
                            HashAlgorithmName.SHA256);

                        byte[] serialNumber = { 1, 1, 2, 3, 5, 8, 13 };

                        AssertExtensions.Throws <ArgumentException>("issuerCertificate", () => request.Create(cert, now, now.AddHours(3), serialNumber));

                        X509SignatureGenerator ecdsaGenerator =
                            X509SignatureGenerator.CreateForECDsa(ecdsa);

                        // Passes with the generator
                        using (request.Create(cert.SubjectName, ecdsaGenerator, now, now.AddHours(3), serialNumber))
                        {
                        }
                    }
                }
        }
Beispiel #4
0
        public static byte[] Sign(byte[] message, byte[] prikey, byte[] pubkey)
        {
            var             signer = SignerUtilities.GetSigner("SHA256withECDSA");
            var             curve  = NistNamedCurves.GetByName("P-256");
            var             dom    = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H);
            ECKeyParameters privateKeyParameters = new ECPrivateKeyParameters(new BigInteger(1, prikey), dom);

            signer.Init(true, privateKeyParameters);
            signer.BlockUpdate(message, 0, message.Length);
            var sig = signer.GenerateSignature();

            return(TranscodeSignatureToConcat(sig, 64));

#if OLD_VERSION
#if NET461
            const int ECDSA_PRIVATE_P256_MAGIC = 0x32534345;
            prikey = BitConverter.GetBytes(ECDSA_PRIVATE_P256_MAGIC).Concat(BitConverter.GetBytes(32)).Concat(pubkey).Concat(prikey).ToArray();
            using (CngKey key = CngKey.Import(prikey, CngKeyBlobFormat.EccPrivateBlob))
                using (ECDsaCng ecdsa = new ECDsaCng(key))
                {
                    return(ecdsa.SignData(message, HashAlgorithmName.SHA256));
                }
#else
            using (var ecdsa = ECDsa.Create(new ECParameters
            {
                Curve = ECCurve.NamedCurves.nistP256,
                D = prikey,
                Q = new ECPoint
                {
                    X = pubkey.Take(32).ToArray(),
                    Y = pubkey.Skip(32).ToArray()
                }
            }))
            {
                return(ecdsa.SignData(message, HashAlgorithmName.SHA256));
            }
#endif
#endif
        }
Beispiel #5
0
            public static X509Certificate2 GetSelfSigned13ServerCertificate()
            {
                if (s_selfSigned13ServerCertificate == null)
                {
                    X509Certificate2 cert;

                    using (ECDsa dsa = ECDsa.Create())
                    {
                        var certReq = new CertificateRequest("CN=testservereku.contoso.com", dsa, HashAlgorithmName.SHA256);
                        certReq.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, false));
                        certReq.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(new OidCollection {
                            new Oid("1.3.6.1.5.5.7.3.1")
                        }, false));
                        certReq.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature, false));

                        X509Certificate2 innerCert = certReq.CreateSelfSigned(DateTimeOffset.UtcNow.AddMonths(-1), DateTimeOffset.UtcNow.AddMonths(1));

                        if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                        {
                            using (innerCert)
                            {
                                cert = new X509Certificate2(innerCert.Export(X509ContentType.Pfx));
                            }
                        }
                        else
                        {
                            cert = innerCert;
                        }
                    }

                    if (Interlocked.CompareExchange(ref s_selfSigned13ServerCertificate, cert, null) != null)
                    {
                        // Lost a race to create.
                        cert.Dispose();
                    }
                }

                return(new X509Certificate2(s_selfSigned13ServerCertificate));
            }
        public void ExportPkcs8PrivateKey(AsnFormat format)
        {
            using ECDsa ecdsa = ECDsa.Create(ECCurve.NamedCurves.nistP256);
            byte[] exported = ecdsa.ExportPkcs8PrivateKey(format);

            if (format == AsnFormat.Der)
            {
                var info = PrivateKeyFactory.CreateKey(exported);
                Assert.IsNotNull(info);
            }

            if (format == AsnFormat.Pem)
            {
                using MemoryStream ms = new MemoryStream(exported);
                using TextReader tr   = new StreamReader(ms, Encoding.ASCII);
                PemReader pemReader = new PemReader(tr);
                object    obj       = pemReader.ReadObject();
                Assert.IsNotNull(obj);
            }

            this.CheckFormat(format, exported);
        }
Beispiel #7
0
        public static string Sign(string apiKey, string data)
        {
            var digest  = SHA256.Create().ComputeHash(Encoding.ASCII.GetBytes(data));
            var keyInfo = ASN1.ParseASN1String(apiKey);

            if (!ASN1.NIST_P_256_CURVE.Equals(keyInfo.CurveNameHex, StringComparison.InvariantCultureIgnoreCase))
            {
                throw new NotSupportedException("Curves other than NIST P256 are not supported");
            }
            var q = new ECPoint {
                X = keyInfo.Qx, Y = keyInfo.Qy
            };
            var d        = keyInfo.PrivateKey;
            var ecParams = new ECParameters {
                D = d, Curve = ECCurve.NamedCurves.nistP256, Q = q
            };

            using (var dsa = ECDsa.Create(ecParams))
            {
                return(Utils.ByteArrayToHexString(dsa.SignHash(digest)));
            }
        }
Beispiel #8
0
        /// <inheritdoc/>
        public override X509Certificate2 CreateForECDsa(X509SignatureGenerator generator)
        {
            if (IssuerCAKeyCert == null)
            {
                throw new NotSupportedException("X509 Signature generator requires an issuer certificate.");
            }

            if (m_ecdsaPublicKey == null && m_curve == null)
            {
                throw new NotSupportedException("Need a public key or a ECCurve to create the certificate.");
            }

            CreateDefaults();

            ECDsa key       = null;
            ECDsa publicKey = m_ecdsaPublicKey;

            if (publicKey == null)
            {
                key       = ECDsa.Create((ECCurve)m_curve);
                publicKey = key;
            }

            var request = new CertificateRequest(SubjectName, publicKey, HashAlgorithmName);

            CreateX509Extensions(request, true);

            X509Certificate2 signedCert = request.Create(
                IssuerCAKeyCert.SubjectName,
                generator,
                NotBefore,
                NotAfter,
                m_serialNumber.Reverse().ToArray()
                );

            // return a X509Certificate2
            return((key == null) ? signedCert : signedCert.CopyWithPrivateKey(key));
        }
        public static void SignatureAlgorithm_Encoding(string hashAlgorithmName)
        {
            string expectedAlgOid;

            switch (hashAlgorithmName)
            {
            case "SHA1":
                expectedAlgOid = "06072A8648CE3D0401";
                break;

            case "SHA256":
                expectedAlgOid = "06082A8648CE3D040302";
                break;

            case "SHA384":
                expectedAlgOid = "06082A8648CE3D040303";
                break;

            case "SHA512":
                expectedAlgOid = "06082A8648CE3D040304";
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(hashAlgorithmName));
            }

            EccTestData testData = EccTestData.Secp521r1Data;

            string expectedHex = $"30{(expectedAlgOid.Length / 2):X2}{expectedAlgOid}";

            using (ECDsa ecdsa = ECDsa.Create(testData.KeyParameters))
            {
                var    generator = X509SignatureGenerator.CreateForECDsa(ecdsa);
                byte[] sigAlg    = generator.GetSignatureAlgorithmIdentifier(new HashAlgorithmName(hashAlgorithmName));

                Assert.Equal(expectedHex, sigAlg.ByteArrayToHex());
            }
        }
        public static void ECDSA_Signing_UnknownPublicKeyAlgorithm()
        {
            using ECDsa ecdsa = ECDsa.Create(ECCurve.NamedCurves.nistP256);
            PublicKey gostRPublicKey = PublicKey.CreateFromSubjectPublicKeyInfo(
                TestData.GostR3410SubjectPublicKeyInfo,
                out _);

            CertificateRequest issuerRequest = new CertificateRequest(
                new X500DistinguishedName("CN=root"),
                ecdsa,
                HashAlgorithmName.SHA256);

            issuerRequest.CertificateExtensions.Add(
                new X509BasicConstraintsExtension(true, false, 0, true));

            CertificateRequest request = new CertificateRequest(
                new X500DistinguishedName("CN=test"),
                gostRPublicKey,
                HashAlgorithmName.SHA256);

            request.CertificateExtensions.Add(
                new X509BasicConstraintsExtension(false, false, 0, true));

            DateTimeOffset notBefore = DateTimeOffset.UtcNow;
            DateTimeOffset notAfter  = notBefore.AddDays(30);

            byte[] serial = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };

            using X509Certificate2 issuer = issuerRequest.CreateSelfSigned(notBefore, notAfter);

            X509SignatureGenerator ecdsaGenerator = X509SignatureGenerator.CreateForECDsa(ecdsa);

            using X509Certificate2 cert = request.Create(issuer.SubjectName, ecdsaGenerator, notBefore, notAfter, serial);

            Assert.Null(cert.GetECDsaPublicKey());
            Assert.Null(cert.GetECDiffieHellmanPublicKey());
            Assert.Equal("1.2.643.2.2.19", cert.PublicKey.Oid.Value);
        }
Beispiel #11
0
        static void CreateCertificate(string path, string password = null)
        {
            var ecdsa = ECDsa.Create();

            var request = new CertificateRequest("CN=testcert, O=GIBZ, L=Zug, S=Zug, C=CH", ecdsa, HashAlgorithmName.SHA512);

            var cert = request.CreateSelfSigned(DateTimeOffset.Now, DateTimeOffset.Now.AddYears(1));

            byte[] exportedCert = null;
            if (password == null)
            {
                exportedCert = cert.Export(X509ContentType.Pfx);
            }
            else
            {
                exportedCert = cert.Export(X509ContentType.Pfx, password);
            }
            if (!Directory.Exists(Path.GetDirectoryName(path)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(path));
            }
            File.WriteAllBytes(path, exportedCert);
        }
Beispiel #12
0
        public static X509Certificate2 Create(string cn, X509KeyUsageFlags?usageFlags = null, string extraKeyUsageOids = null)
        {
            using ECDsa elipticKey = ECDsa.Create(ECCurve.NamedCurves.nistP256);

            CertificateRequest request = new CertificateRequest($"CN={cn}; C=SK", elipticKey, HashAlgorithmName.SHA256);

            if (usageFlags.HasValue)
            {
                request.CertificateExtensions.Add(new X509KeyUsageExtension(usageFlags.Value, false));
            }

            if (!string.IsNullOrEmpty(extraKeyUsageOids))
            {
                OidCollection oidCollection = new OidCollection();
                foreach (string oid in extraKeyUsageOids.Split(new char[] { ';', ',' }))
                {
                    oidCollection.Add(new Oid(oid.Trim()));
                }
                request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(oidCollection, false));
            }

            return(request.CreateSelfSigned(DateTime.Now.AddDays(-1.0), DateTime.Now.AddDays(1.0)));
        }
Beispiel #13
0
        private void CreateSelfSignedCert(string certName)
        {
            ECDsa ecdsaKey = ECDsa.Create();
            CertificateRequest certificateRequest = new CertificateRequest(certName, ecdsaKey, HashAlgorithmName.SHA256);
            // We have to export cert to dummy cert since `CreateSelfSigned` creates a cert without a private key.
            X509Certificate2 cert = certificateRequest.CreateSelfSigned(DateTimeOffset.Now, DateTimeOffset.Now.AddYears(5));

            X509Certificate2 dummyCert = null;

            if (PowerShell.Authentication.Helpers.OperatingSystem.IsMacOS())
            {
                dummyCert = new X509Certificate2(cert.Export(X509ContentType.Pfx, "P@55w0rd"), "P@55w0rd", X509KeyStorageFlags.Exportable);
            }
            else
            {
                dummyCert = new X509Certificate2(cert.Export(X509ContentType.Pfx, "P@55w0rd"), "P@55w0rd", X509KeyStorageFlags.PersistKeySet);
            }
            using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser))
            {
                store.Open(OpenFlags.ReadWrite);
                store.Add(dummyCert);
            }
        }
        /// <summary>
        /// Create a Self signed certificate with all options which can also be used as a root certificate
        /// </summary>
        /// <param name="distinguishedName">Distinguished Name used for the subject and the issuer properties</param>
        /// <param name="validityPeriod">Valid from, Valid to certificate properties</param>
        /// <param name="subjectAlternativeName">SAN but only DnsNames can be added as a list + Email property</param>
        /// <param name="enhancedKeyUsages">Defines how the certificate key can be used.
        /// OidLookup.ServerAuthentication,
        /// OidLookup.ClientAuthentication,
        /// OidLookup.CodeSigning,
        /// OidLookup.SecureEmail,
        /// OidLookup.TimeStamping
        /// </param>
        /// <param name="x509KeyUsageFlags">Defines how the certificate key can be used.
        ///  None             No key usage parameters.
        ///  EncipherOnly     The key can be used for encryption only.
        ///  CrlSign          The key can be used to sign a certificate revocation list (CRL).
        ///  KeyCertSign      The key can be used to sign certificates.
        ///  KeyAgreement     The key can be used to determine key agreement, such as a key created using the Diffie-Hellman key agreement algorithm.
        ///  DataEncipherment The key can be used for data encryption.
        ///  KeyEncipherment  The key can be used for key encryption.
        ///  NonRepudiation   The key can be used for authentication.
        ///  DecipherOnly     The key can be used for decryption only.
        ///  </param>
        /// <returns>Self signed certificate</returns>
        public X509Certificate2 NewECDsaSelfSignedCertificate(
            DistinguishedName distinguishedName,
            BasicConstraints basicConstraints,
            ValidityPeriod validityPeriod,
            SubjectAlternativeName subjectAlternativeName,
            OidCollection enhancedKeyUsages,
            X509KeyUsageFlags x509KeyUsageFlags,
            ECDsaConfiguration eCDsaConfiguration)
        {
            using var ecdsa = ECDsa.Create("ECDsa");
            ecdsa.KeySize   = eCDsaConfiguration.KeySize;
            var request = new CertificateRequest(
                _certificateUtility.CreateIssuerOrSubject(distinguishedName),
                ecdsa,
                eCDsaConfiguration.HashAlgorithmName);

            return(NewECDsaSelfSignedCertificate(basicConstraints,
                                                 validityPeriod,
                                                 subjectAlternativeName,
                                                 enhancedKeyUsages,
                                                 x509KeyUsageFlags,
                                                 request));
        }
Beispiel #15
0
        private ECDsa ConvertToSingKeyFormat(AsymmetricCipherKeyPair key)
        {
            ECPublicKeyParameters  pubAsyKey  = (ECPublicKeyParameters)key.Public;
            ECPrivateKeyParameters privAsyKey = (ECPrivateKeyParameters)key.Private;

            var signParam = new ECParameters
            {
                Curve = ECCurve.NamedCurves.nistP256,
                Q     =
                {
                    X = pubAsyKey.Q.AffineXCoord.GetEncoded(),
                    Y = pubAsyKey.Q.AffineYCoord.GetEncoded()
                }
            };

            signParam.D = CryptoUtils.FixDSize(privAsyKey.D.ToByteArrayUnsigned(), signParam.Q.X.Length);
            signParam.Validate();

            X = pubAsyKey.Q.AffineXCoord.GetEncoded();
            Y = pubAsyKey.Q.AffineYCoord.GetEncoded();

            return(ECDsa.Create(signParam));
        }
Beispiel #16
0
        public static bool Verify(ReadOnlyMemory <byte> publicKey, ReadOnlyMemory <byte> signature, ReadOnlySequence <byte> sequence)
        {
            ECParameters ecParameters;

            {
                var plist = SerializeHelper.Decode(publicKey).ToArray();

                ecParameters = new ECParameters()
                {
                    Q = new ECPoint()
                    {
                        X = plist[0].ToArray(),
                        Y = plist[1].ToArray(),
                    },
                };
            }

            using (var ecdsa = ECDsa.Create())
            {
                ecdsa.ImportParameters(ecParameters);
                return(ecdsa.VerifyHash(Sha2_256.ComputeHash(sequence).AsSpan(), signature.Span));
            }
        }
Beispiel #17
0
                public _signatureProvider(SecurityKey key, string algorithm) : base(key, algorithm)
                {
                    _key = key as JsonWebKey;
                    if (_key.Kty == JsonWebAlgorithmsKeyTypes.EllipticCurve)
                    {
                        var ecpa = new ECParameters
                        {
                            Curve             = _curves[_key.Crv],
                            D                 = _key.D != null?Base64UrlEncoder.DecodeBytes(_key.D) : null,
                                            Q = new ECPoint
                            {
                                X = Base64UrlEncoder.DecodeBytes(_key.X),
                                Y = Base64UrlEncoder.DecodeBytes(_key.Y)
                            }
                        };

                        _ecdsa = ECDsa.Create(ecpa);
                    }
                    else
                    {
                        throw new InvalidOperationException("Algorithm not yet supported");
                    }
                }
Beispiel #18
0
        public static void DecryptUsingWrongPrivateKeyType()
        {
            byte[]              content     = new byte[] { 1, 2, 3, 4 };
            ContentInfo         contentInfo = new ContentInfo(content);
            AlgorithmIdentifier alg         = new AlgorithmIdentifier(new Oid(Oids.Aes192));

            EnvelopedCms ecms = new EnvelopedCms(contentInfo, alg);

            using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate())
            {
                CmsRecipient cmsRecipient = new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, cert);
                ecms.Encrypt(cmsRecipient);
            }

            byte[] encoded = ecms.Encode();
            ecms = new EnvelopedCms();
            ecms.Decode(encoded);

            using (ECDsa ecdsa = ECDsa.Create())
            {
                Assert.Throws <CryptographicException>(() => ecms.Decrypt(ecms.RecipientInfos[0], ecdsa));
            }
        }
Beispiel #19
0
        /// <summary>
        /// 根据传入的公私钥,对可签名的对象进行签名
        /// </summary>
        /// <param name="signable">要签名的数据</param>
        /// <param name="prikey">私钥</param>
        /// <param name="pubkey">公钥</param>
        /// <returns>返回签名后的结果</returns>
        internal static byte[] Sign(this ISignable signable, byte[] prikey, byte[] pubkey)
        {
#if NET461
            const int ECDSA_PRIVATE_P256_MAGIC = 0x32534345;
            prikey = BitConverter.GetBytes(ECDSA_PRIVATE_P256_MAGIC).Concat(BitConverter.GetBytes(32)).Concat(pubkey).Concat(prikey).ToArray();
            using (CngKey key = CngKey.Import(prikey, CngKeyBlobFormat.EccPrivateBlob))
                using (ECDsaCng ecdsa = new ECDsaCng(key))
#else
            using (var ecdsa = ECDsa.Create(new ECParameters
            {
                Curve = ECCurve.NamedCurves.nistP256,
                D = prikey,
                Q = new ECPoint
                {
                    X = pubkey.Take(32).ToArray(),
                    Y = pubkey.Skip(32).ToArray()
                }
            }))
#endif
                {
                    return(ecdsa.SignHash(signable.GetHashForSigning()));
                }
        }
Beispiel #20
0
        /// <summary>
        /// 根据传入的公钥与签名,对可签名对象的签名进行验证
        /// </summary>
        /// <param name="signable">要验证的数据</param>
        /// <param name="pubkey">公钥</param>
        /// <param name="signature">签名</param>
        /// <returns>返回验证结果</returns>
        public static bool VerifySignature(this ISignable signable, Cryptography.ECC.ECPoint pubkey, byte[] signature)
        {
            byte[] pubk = pubkey.EncodePoint(false).Skip(1).ToArray();
#if NET461
            const int ECDSA_PUBLIC_P256_MAGIC = 0x31534345;
            pubk = BitConverter.GetBytes(ECDSA_PUBLIC_P256_MAGIC).Concat(BitConverter.GetBytes(32)).Concat(pubk).ToArray();
            using (CngKey key = CngKey.Import(pubk, CngKeyBlobFormat.EccPublicBlob))
                using (ECDsaCng ecdsa = new ECDsaCng(key))
#else
            using (var ecdsa = ECDsa.Create(new ECParameters
            {
                Curve = ECCurve.NamedCurves.nistP256,
                Q = new ECPoint
                {
                    X = pubk.Take(32).ToArray(),
                    Y = pubk.Skip(32).ToArray()
                }
            }))
#endif
                {
                    return(ecdsa.VerifyHash(signable.GetHashForSigning(), signature));
                }
        }
Beispiel #21
0
        /// <summary>
        /// Gets a signing key based on settings
        /// </summary>
        /// <param name="settings">The identity settings</param>
        /// <returns></returns>
        private static ECDsaSecurityKey GetSigningKey(IdentitySettings settings)
        {
            // source directory
            var sourceDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? string.Empty;

            // build full path to key
            var fullKeyPath = Path.GetFullPath(settings.SigningKeyPath, sourceDirectory);

            // read signing key path to load key
            var eccPem = File.ReadAllText(fullKeyPath);

            // build key and import
            var edc = ECDsa.Create();

            // import pem content into key
            edc?.ImportFromPem(eccPem);

            // create a security key based on ECD
            return(new ECDsaSecurityKey(edc)
            {
                KeyId = "default"
            });
        }
Beispiel #22
0
        public byte[] Sign(byte[] message, byte[] prikey, byte[] pubkey)
        {
#if NET461
            const int ECDSA_PRIVATE_P256_MAGIC = 0x32534345;
            prikey = BitConverter.GetBytes(ECDSA_PRIVATE_P256_MAGIC).Concat(BitConverter.GetBytes(32)).Concat(pubkey).Concat(prikey).ToArray();
            using (CngKey key = CngKey.Import(prikey, CngKeyBlobFormat.EccPrivateBlob))
                using (ECDsaCng ecdsa = new ECDsaCng(key))
#else
            using (var ecdsa = ECDsa.Create(new ECParameters
            {
                Curve = ECCurve.NamedCurves.nistP256,
                D = prikey,
                Q = new ECPoint
                {
                    X = pubkey.Take(32).ToArray(),
                    Y = pubkey.Skip(32).ToArray()
                }
            }))
#endif
                {
                    return(ecdsa.SignData(message, HashAlgorithmName.SHA256));
                }
        }
        public static void ECDSA_Signing_ECDSA_NoKeyUsageValidForECDSAAndECDH()
        {
            using ECDsa ecdsa     = ECDsa.Create(ECCurve.NamedCurves.nistP256);
            using ECDsa ecdsaLeaf = ECDsa.Create(ECCurve.NamedCurves.nistP256);

            CertificateRequest issuerRequest = new CertificateRequest(
                new X500DistinguishedName("CN=root"),
                ecdsa,
                HashAlgorithmName.SHA256);

            issuerRequest.CertificateExtensions.Add(
                new X509BasicConstraintsExtension(true, false, 0, true));

            CertificateRequest request = new CertificateRequest(
                new X500DistinguishedName("CN=test"),
                ecdsaLeaf,
                HashAlgorithmName.SHA256);

            request.CertificateExtensions.Add(
                new X509BasicConstraintsExtension(false, false, 0, true));

            DateTimeOffset notBefore = DateTimeOffset.UtcNow;
            DateTimeOffset notAfter  = notBefore.AddDays(30);

            byte[] serial = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };

            using X509Certificate2 issuer           = issuerRequest.CreateSelfSigned(notBefore, notAfter);
            using X509Certificate2 cert             = request.Create(issuer, notBefore, notAfter, serial);
            using ECDiffieHellman publicCertEcDhKey = cert.GetECDiffieHellmanPublicKey();
            using ECDsa publicCertEcDsaKey          = cert.GetECDsaPublicKey();
            byte[] expectedSubjectPublicKeyInfo = ecdsaLeaf.ExportSubjectPublicKeyInfo();

            Assert.NotNull(publicCertEcDhKey);
            Assert.NotNull(publicCertEcDsaKey);
            Assert.Equal(expectedSubjectPublicKeyInfo, publicCertEcDhKey.ExportSubjectPublicKeyInfo());
            Assert.Equal(expectedSubjectPublicKeyInfo, publicCertEcDsaKey.ExportSubjectPublicKeyInfo());
        }
Beispiel #24
0
        public void FromECDsaP384()
        {
#if (NET45 || NETCOREAPP1_1)
            Assert.Inconclusive("ECDsa is not available.");
#else
            // From https://tools.ietf.org/html/rfc6605#section-6.2
            var privateKey   = Convert.FromBase64String("WURgWHCcYIYUPWgeLmiPY2DJJk02vgrmTfitxgqcL4vwW7BOrbawVmVe0d9V94SR");
            var dnsPublicKey = Convert.FromBase64String("xKYaNhWdGOfJ+nPrL8/arkwf2EY3MDJ+SErKivBVSum1w/egsXvSADtNJhyem5RCOpgQ6K8X1DRSEkrbYQ+OB+v8/uX45NBwY8rp65F6Glur8I/mlVNgF6W/qTI37m40");
            var qx           = new byte[48];
            var qy           = new byte[48];
            Array.Copy(dnsPublicKey, 0, qx, 0, 48);
            Array.Copy(dnsPublicKey, 48, qy, 0, 48);

            // Create the public key
            var parameters = new ECParameters
            {
                Curve = ECCurve.NamedCurves.nistP384,
                Q     = new ECPoint
                {
                    X = qx,
                    Y = qy,
                }
            };
            ECDsa publicKey = ECDsa.Create(parameters);

            var dnskey = new DNSKEYRecord(publicKey)
            {
                Flags = DNSKEYFlags.ZoneKey | DNSKEYFlags.SecureEntryPoint
            };
            Assert.AreEqual(DNSKEYFlags.ZoneKey | DNSKEYFlags.SecureEntryPoint, dnskey.Flags);
            Assert.AreEqual(3, dnskey.Protocol);
            Assert.AreEqual(SecurityAlgorithm.ECDSAP384SHA384, dnskey.Algorithm);
            CollectionAssert.AreEqual(dnsPublicKey, dnskey.PublicKey);
            Assert.AreEqual(10771, dnskey.KeyTag());
#endif
        }
Beispiel #25
0
        public void FromECDsaP256()
        {
#if (NET45 || NETCOREAPP1_1)
            Assert.Inconclusive("ECDsa is not available.");
#else
            // From https://tools.ietf.org/html/rfc6605#section-6.1
            var privateKey   = Convert.FromBase64String("GU6SnQ/Ou+xC5RumuIUIuJZteXT2z0O/ok1s38Et6mQ=");
            var dnsPublicKey = Convert.FromBase64String("GojIhhXUN/u4v54ZQqGSnyhWJwaubCvTmeexv7bR6edbkrSqQpF64cYbcB7wNcP+e+MAnLr+Wi9xMWyQLc8NAA==");
            var qx           = new byte[32];
            var qy           = new byte[32];
            Array.Copy(dnsPublicKey, 0, qx, 0, 32);
            Array.Copy(dnsPublicKey, 32, qy, 0, 32);

            // Create the public key
            var parameters = new ECParameters
            {
                Curve = ECCurve.NamedCurves.nistP256,
                Q     = new ECPoint
                {
                    X = qx,
                    Y = qy,
                }
            };
            ECDsa publicKey = ECDsa.Create(parameters);

            var dnskey = new DNSKEYRecord(publicKey)
            {
                Flags = DNSKEYFlags.ZoneKey | DNSKEYFlags.SecureEntryPoint
            };
            Assert.AreEqual(DNSKEYFlags.ZoneKey | DNSKEYFlags.SecureEntryPoint, dnskey.Flags);
            Assert.AreEqual(3, dnskey.Protocol);
            Assert.AreEqual(SecurityAlgorithm.ECDSAP256SHA256, dnskey.Algorithm);
            CollectionAssert.AreEqual(dnsPublicKey, dnskey.PublicKey);
            Assert.AreEqual(55648, dnskey.KeyTag());
#endif
        }
Beispiel #26
0
 /// <summary>
 /// 验证签名
 /// </summary>
 /// <param name="message">已签名的数据</param>
 /// <param name="signature">要验证的签名数据</param>
 /// <param name="pubkey">公钥地址,是由02和03组成的</param>
 /// <returns></returns>
 public bool VerifySignature(byte[] message, byte[] signature, byte[] pubkey)
 {
     if (pubkey.Length == 33 && (pubkey[0] == 0x02 || pubkey[0] == 0x03))
     {
         try
         {
             pubkey = Cryptography.ECC.ECPoint.DecodePoint(pubkey, Cryptography.ECC.ECCurve.Secp256r1).EncodePoint(false).Skip(1).ToArray();
         }
         catch
         {
             return(false);
         }
     }
     else if (pubkey.Length == 65 && pubkey[0] == 0x04)
     {
         pubkey = pubkey.Skip(1).ToArray();
     }
     else if (pubkey.Length != 64)
     {
         throw new ArgumentException();
     }
     using (var ecdsa = ECDsa.Create(new ECParameters
     {
         Curve = ECCurve.NamedCurves.nistP256, //表示与公钥 (Q) 和可选私钥 (D) 相关联的曲线
         Q = new ECPoint                       //表示椭圆曲线加密 (ECC) 算法的公钥 Q。表示椭圆曲线加密 (ECC) 结构的 (X,Y) 坐标对
         {
             X = pubkey.Take(32).ToArray(),    //表示 X 坐标,公钥前32个字节
             Y = pubkey.Skip(32).ToArray()     //	表示 Y 坐标,公钥32个字节之后的数据
         }
     }))
     {
         //通过使用指定的哈希算法计算指定数据的哈希值,并将其与提供的签名进行比较,
         //验证数字签名是否有效
         return(ecdsa.VerifyData(message, signature, HashAlgorithmName.SHA256));
     }
 }
Beispiel #27
0
        public static void SelfSign_ECC_DiminishedPoint_UseCertKeys()
        {
            X509Certificate2 cert;
            ECParameters     pubParams;

            ECDsa priv2;

            using (ECDsa ecdsa = ECDsa.Create(EccTestData.Secp521r1_DiminishedPublic_Data.KeyParameters))
            {
                pubParams = ecdsa.ExportParameters(false);

                CertificateRequest request = new CertificateRequest(
                    "CN=localhost, OU=.NET Framework (CoreFX), O=Microsoft Corporation, L=Redmond, S=Washington, C=US",
                    ecdsa,
                    HashAlgorithmName.SHA512);

                DateTimeOffset now = DateTimeOffset.UtcNow;
                cert = request.CreateSelfSigned(now, now.AddDays(90));

                priv2 = cert.GetECDsaPrivateKey();
            }

            using (cert)
                using (priv2)
                    using (ECDsa pub = ECDsa.Create(pubParams))
                    {
                        Assert.True(cert.HasPrivateKey, "cert.HasPrivateKey");
                        Assert.NotNull(priv2);

                        byte[] sig = priv2.SignData(pubParams.Q.X, HashAlgorithmName.SHA384);

                        Assert.True(
                            pub.VerifyData(pubParams.Q.X, sig, HashAlgorithmName.SHA384),
                            "Cert signature validates with public key");
                    }
        }
Beispiel #28
0
        public void GenerateAndSign()
        {
            var ecdsa = ECDsa.Create(ECCurve.NamedCurves.nistP256);

            // generate a key ring
            string passPhrase = "test";
            var    keyRingGen = new PgpKeyRingGenerator(ecdsa, "*****@*****.**", passPhrase);

            PgpPublicKeyRing pubRing = keyRingGen.GeneratePublicKeyRing();
            PgpSecretKeyRing secRing = keyRingGen.GenerateSecretKeyRing();

            KeyTestHelper.SignAndVerifyTestMessage(secRing.GetSecretKey().ExtractPrivateKey(passPhrase), pubRing.GetPublicKey());

            PgpPublicKeyRing pubRingEnc = new PgpPublicKeyRing(pubRing.GetEncoded());

            Assert.AreEqual(pubRing.GetEncoded(), pubRingEnc.GetEncoded(), "public key ring encoding failed");

            PgpSecretKeyRing secRingEnc = new PgpSecretKeyRing(secRing.GetEncoded());

            Assert.AreEqual(secRing.GetEncoded(), secRingEnc.GetEncoded(), "secret key ring encoding failed");

            // try a signature using encoded key
            KeyTestHelper.SignAndVerifyTestMessage(secRing.GetSecretKey().ExtractPrivateKey(passPhrase), secRing.GetSecretKey());
        }
Beispiel #29
0
        public ISignatureAlgorithm ToSignatureAlgorithm(ClientDataRecord dataRecord, SharedSecretEncryptionKey encryptionKey)
        {
            if (dataRecord == null)
            {
                throw new ArgumentNullException(nameof(dataRecord));
            }

            switch (dataRecord.SigType)
            {
            case string str when str.Equals("rsa", StringComparison.OrdinalIgnoreCase):
                using (var rsaForVerification = new RSACryptoServiceProvider())
                {
                    rsaForVerification.FromXml(dataRecord.SigParameter);
                    var paramsForVerification = rsaForVerification.ExportParameters(false);

                    return(SignatureAlgorithm.CreateForVerification(paramsForVerification, new HashAlgorithmName(dataRecord.SigHashAlgorithm)));
                }

            case string str when str.Equals("ecdsa", StringComparison.OrdinalIgnoreCase):
                using (var ecdsaForVerification = ECDsa.Create())
                {
                    ecdsaForVerification.FromXml(dataRecord.SigParameter);
                    var paramsForVerification = ecdsaForVerification.ExportParameters(false);

                    return(SignatureAlgorithm.CreateForVerification(paramsForVerification, new HashAlgorithmName(dataRecord.SigHashAlgorithm)));
                }

            case string str when str.Equals("hmac", StringComparison.OrdinalIgnoreCase):
                var unencryptedKey = GetUnencryptedParameter(dataRecord, encryptionKey);

                return(SignatureAlgorithm.CreateForVerification(unencryptedKey, new HashAlgorithmName(dataRecord.SigHashAlgorithm)));

            default:
                throw new NotSupportedException($"The specified signature algorithm type ({dataRecord.SigHashAlgorithm ?? "[null]"}) cannot be deserialized.");
            }
        }
        /// <inheritdoc/>
        public override AsymmetricSecurityKey ToSecurityKey()
        {
            var curve = Algorithm switch
            {
                "ES256" => "P-256",
                "ES384" => "P-384",
                "ES512" => "P-521",
                _ => throw new Exception("Invalid SigningAlgorithm")
            };

            var parameters = new ECParameters {
                Curve = CryptoHelper.GetCurveFromCrvValue(curve),
                D     = D,
                Q     = Q,
            };

            var key = new ECDsaSecurityKey(ECDsa.Create(parameters))
            {
                KeyId = Id
            };

            return(key);
        }
    }