public static void SerialNumber_AlwaysPositive() { using (ECDsa ecdsa = ECDsa.Create(EccTestData.Secp521r1_DiminishedPublic_Data.KeyParameters)) { var generator = X509SignatureGenerator.CreateForECDsa(ecdsa); CertificateRequest request = new CertificateRequest( new X500DistinguishedName("CN=Test Cert"), generator.PublicKey, HashAlgorithmName.SHA512); byte[] desiredSerial = { 0x80 }; DateTimeOffset now = DateTimeOffset.UtcNow; X509Certificate2 cert = request.Create( request.SubjectName, generator, now, now.AddDays(1), desiredSerial); using (cert) { Assert.Equal("0080", cert.SerialNumber); } } }
public static void CtorValidation_PublicKey_X500DN() { X500DistinguishedName subjectName = null; PublicKey publicKey = null; HashAlgorithmName hashAlgorithm = default(HashAlgorithmName); AssertExtensions.Throws <ArgumentNullException>( "subjectName", () => new CertificateRequest(subjectName, publicKey, hashAlgorithm)); subjectName = new X500DistinguishedName(""); AssertExtensions.Throws <ArgumentNullException>( "publicKey", () => new CertificateRequest(subjectName, publicKey, hashAlgorithm)); using (ECDsa ecdsa = ECDsa.Create(EccTestData.Secp384r1Data.KeyParameters)) { X509SignatureGenerator generator = X509SignatureGenerator.CreateForECDsa(ecdsa); publicKey = generator.PublicKey; } AssertExtensions.Throws <ArgumentException>( "hashAlgorithm", () => new CertificateRequest(subjectName, publicKey, hashAlgorithm)); }
public static void PublicKeyEncoding(EccTestData testData) { ECParameters keyParameters = testData.KeyParameters; using (ECDsa ecdsa = ECDsa.Create(keyParameters)) { X509SignatureGenerator signatureGenerator = X509SignatureGenerator.CreateForECDsa(ecdsa); PublicKey publicKey = signatureGenerator.PublicKey; Assert.Equal( testData.CurveEncodedOidHex, publicKey.EncodedParameters.RawData.ByteArrayToHex()); string expectedKeyHex = // Uncompressed Point "04" + // Qx keyParameters.Q.X.ByteArrayToHex() + // Qy keyParameters.Q.Y.ByteArrayToHex(); Assert.Equal(expectedKeyHex, publicKey.EncodedKeyValue.RawData.ByteArrayToHex()); const string ecPublicKeyOid = "1.2.840.10045.2.1"; Assert.Equal(ecPublicKeyOid, publicKey.Oid.Value); Assert.Equal(ecPublicKeyOid, publicKey.EncodedParameters.Oid.Value); Assert.Equal(ecPublicKeyOid, publicKey.EncodedKeyValue.Oid.Value); PublicKey publicKey2 = signatureGenerator.PublicKey; Assert.Same(publicKey, publicKey2); } }
public void CreateForECDsaWithGeneratorTest( ECCurveHashPair ecCurveHashPair ) { // default signing cert with custom key X509Certificate2 signingCert = CertificateBuilder.Create(Subject) .SetCAConstraint() .SetHashAlgorithm(HashAlgorithmName.SHA512) .SetECCurve(ecCurveHashPair.Curve) .CreateForECDsa(); WriteCertificate(signingCert, $"Signing ECDsa {signingCert.GetECDsaPublicKey().KeySize} cert"); using (ECDsa ecdsaPrivateKey = signingCert.GetECDsaPrivateKey()) { var generator = X509SignatureGenerator.CreateForECDsa(ecdsaPrivateKey); var cert = CertificateBuilder.Create("CN=App Cert") .SetIssuer(new X509Certificate2(signingCert.RawData)) .CreateForRSA(generator); Assert.NotNull(cert); WriteCertificate(cert, "Default signed ECDsa cert"); } using (ECDsa ecdsaPrivateKey = signingCert.GetECDsaPrivateKey()) using (ECDsa ecdsaPublicKey = signingCert.GetECDsaPublicKey()) { var generator = X509SignatureGenerator.CreateForECDsa(ecdsaPrivateKey); var cert = CertificateBuilder.Create("CN=App Cert") .SetHashAlgorithm(ecCurveHashPair.HashAlgorithmName) .SetIssuer(new X509Certificate2(signingCert.RawData)) .SetECDsaPublicKey(ecdsaPublicKey) .CreateForECDsa(generator); Assert.NotNull(cert); WriteCertificate(cert, "Default signed ECDsa cert with Public Key"); } using (ECDsa ecdsaPrivateKey = signingCert.GetECDsaPrivateKey()) { var generator = X509SignatureGenerator.CreateForECDsa(ecdsaPrivateKey); var cert = CertificateBuilder.Create("CN=App Cert") .SetHashAlgorithm(ecCurveHashPair.HashAlgorithmName) .SetIssuer(new X509Certificate2(signingCert.RawData)) .SetECCurve(ecCurveHashPair.Curve) .CreateForECDsa(generator); Assert.NotNull(cert); WriteCertificate(cert, "Default signed RSA cert"); } // ensure invalid path throws argument exception Assert.Throws <NotSupportedException>(() => { using (ECDsa ecdsaPrivateKey = signingCert.GetECDsaPrivateKey()) { var generator = X509SignatureGenerator.CreateForECDsa(ecdsaPrivateKey); var cert = CertificateBuilder.Create("CN=App Cert") .SetHashAlgorithm(ecCurveHashPair.HashAlgorithmName) .SetECCurve(ecCurveHashPair.Curve) .CreateForECDsa(generator); } }); }
public static void Run() { var time = DateTimeOffset.Now; var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); var epochTime = (long)(time - epoch).TotalSeconds; var password = "******"; var caKey = ECDsa.Create(); var caRequest = new CertificateRequest(new X500DistinguishedName("CN=ca.example.org"), caKey, HashAlgorithmName.SHA256); caRequest.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, true, 2, true)); var caCert = caRequest.CreateSelfSigned(time, time.AddDays(365)); File.WriteAllBytes("ca.example.org.pfx", caCert.Export(X509ContentType.Pfx, password)); File.WriteAllBytes("ca.example.org.cer", caCert.Export(X509ContentType.Cert)); var subKey = ECDsa.Create(); var subRequest = new CertificateRequest(new X500DistinguishedName("CN=sub.example.org"), subKey, HashAlgorithmName.SHA256); subRequest.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, true, 1, true)); var subCert = subRequest.Create(caCert, time, time.AddDays(365), BitConverter.GetBytes(epochTime + 1)).CopyWithPrivateKey(subKey); File.WriteAllBytes("sub.example.org.pfx", subCert.Export(X509ContentType.Pfx, password)); File.WriteAllBytes("sub.example.org.cer", subCert.Export(X509ContentType.Cert)); var key = RSA.Create(2048); var request = new CertificateRequest(new X500DistinguishedName("CN=example.org"), key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); var cert = request.Create(subCert.SubjectName, X509SignatureGenerator.CreateForECDsa(subCert.GetECDsaPrivateKey()), time, time.AddDays(365), BitConverter.GetBytes(epochTime + 2)).CopyWithPrivateKey(key); File.WriteAllBytes("example.org.pfx", cert.Export(X509ContentType.Pfx, password)); }
public static void InvalidDerInAttribute() { using (ECDsa key = ECDsa.Create(EccTestData.Secp384r1Data.KeyParameters)) { CertificateRequest req = new CertificateRequest( "CN=Test", key, HashAlgorithmName.SHA384); // This is "legal DER", but contains more than one value, which is invalid in context. ReadOnlySpan <byte> invalidEncoding = new byte[] { // PrintableString("123") 0x13, 0x03, 0x31, 0x32, 0x33, // NULL 0x05, 0x00, }; req.OtherRequestAttributes.Add( new AsnEncodedData( new Oid("1.2.840.113549.1.9.7", null), invalidEncoding)); X509SignatureGenerator gen = X509SignatureGenerator.CreateForECDsa(key); Assert.Throws <CryptographicException>(() => req.CreateSigningRequest()); Assert.Throws <CryptographicException>(() => req.CreateSigningRequest(gen)); } }
public static void ExtensionRequestInAttributeInCollection() { using (ECDsa key = ECDsa.Create(EccTestData.Secp384r1Data.KeyParameters)) { CertificateRequest req = new CertificateRequest( "CN=Test", key, HashAlgorithmName.SHA384); req.OtherRequestAttributes.Add( new AsnEncodedData( new Oid("1.2.840.113549.1.9.14", null), Array.Empty <byte>())); X509SignatureGenerator gen = X509SignatureGenerator.CreateForECDsa(key); InvalidOperationException ex; ex = Assert.Throws <InvalidOperationException>(() => req.CreateSigningRequest()); Assert.Contains(nameof(CertificateRequest.OtherRequestAttributes), ex.Message); Assert.Contains(nameof(CertificateRequest.CertificateExtensions), ex.Message); ex = Assert.Throws <InvalidOperationException>(() => req.CreateSigningRequest(gen)); Assert.Contains(nameof(CertificateRequest.OtherRequestAttributes), ex.Message); Assert.Contains(nameof(CertificateRequest.CertificateExtensions), ex.Message); } }
public static void SignatureAlgorithm_NotSupported(string hashAlgorithmName) { using (ECDsa ecdsa = ECDsa.Create(EccTestData.Secp256r1Data.KeyParameters)) { HashAlgorithmName hashAlgorithm = new HashAlgorithmName(hashAlgorithmName); var generator = X509SignatureGenerator.CreateForECDsa(ecdsa); Assert.Throws <ArgumentOutOfRangeException>( "hashAlgorithm", () => generator.GetSignatureAlgorithmIdentifier(hashAlgorithm)); } }
public static void DisplayCertificateTest() { using (ECDsa ecdsa = ECDsa.Create(EccTestData.Secp256r1Data.KeyParameters)) { CertificateRequest request = new CertificateRequest("CN=Test", ecdsa, HashAlgorithmName.SHA256); DateTimeOffset now = DateTimeOffset.UtcNow; using (X509Certificate2 cert = request.Create(request.SubjectName, X509SignatureGenerator.CreateForECDsa(ecdsa), now, now.AddMinutes(10), new byte[1])) { X509Certificate2UI.DisplayCertificate(cert); } } }
public static void SignatureAlgorithm_StableNotSame(string hashAlgorithmName) { using (ECDsa ecdsa = ECDsa.Create(EccTestData.Secp256r1Data.KeyParameters)) { HashAlgorithmName hashAlgorithm = new HashAlgorithmName(hashAlgorithmName); var generator = X509SignatureGenerator.CreateForECDsa(ecdsa); byte[] sigAlg = generator.GetSignatureAlgorithmIdentifier(hashAlgorithm); byte[] sigAlg2 = generator.GetSignatureAlgorithmIdentifier(hashAlgorithm); Assert.NotSame(sigAlg, sigAlg2); Assert.Equal(sigAlg, sigAlg2); } }
public static X509Certificate2 generateSelfSignedCertificate(string keyId, string subjectDN, Func <List <string>, string> selector) { string signingAlgorithm = null; using (var kmsClient = new AmazonKeyManagementServiceClient()) { GetPublicKeyRequest getPublicKeyRequest = new GetPublicKeyRequest() { KeyId = keyId }; GetPublicKeyResponse getPublicKeyResponse = kmsClient.GetPublicKeyAsync(getPublicKeyRequest).Result; List <string> signingAlgorithms = getPublicKeyResponse.SigningAlgorithms; signingAlgorithm = selector.Invoke(signingAlgorithms); byte[] spkiBytes = getPublicKeyResponse.PublicKey.ToArray(); CertificateRequest certificateRequest = null; X509SignatureGenerator simpleGenerator = null; string keySpecString = getPublicKeyResponse.CustomerMasterKeySpec.ToString(); if (keySpecString.StartsWith("ECC")) { ECDsa ecdsa = ECDsa.Create(); int bytesRead = 0; ecdsa.ImportSubjectPublicKeyInfo(new ReadOnlySpan <byte>(spkiBytes), out bytesRead); certificateRequest = new CertificateRequest(subjectDN, ecdsa, getHashAlgorithmName(signingAlgorithm)); simpleGenerator = X509SignatureGenerator.CreateForECDsa(ecdsa); } else if (keySpecString.StartsWith("RSA")) { RSA rsa = RSA.Create(); int bytesRead = 0; rsa.ImportSubjectPublicKeyInfo(new ReadOnlySpan <byte>(spkiBytes), out bytesRead); RSASignaturePadding rsaSignaturePadding = getSignaturePadding(signingAlgorithm); certificateRequest = new CertificateRequest(subjectDN, rsa, getHashAlgorithmName(signingAlgorithm), rsaSignaturePadding); simpleGenerator = X509SignatureGenerator.CreateForRSA(rsa, rsaSignaturePadding); } else { throw new ArgumentException("Cannot determine encryption algorithm for " + keySpecString, nameof(keyId)); } X509SignatureGenerator generator = new SignatureGenerator(keyId, signingAlgorithm, simpleGenerator); X509Certificate2 certificate = certificateRequest.Create(new X500DistinguishedName(subjectDN), generator, System.DateTimeOffset.Now, System.DateTimeOffset.Now.AddYears(2), new byte[] { 17 }); return(certificate); } }
private static X509SignatureGenerator OpenGenerator(AsymmetricAlgorithm key) { RSA rsa = key as RSA; if (rsa != null) { return(X509SignatureGenerator.CreateForRSA(rsa, RSASignaturePadding.Pkcs1)); } ECDsa ecdsa = key as ECDsa; if (ecdsa != null) { return(X509SignatureGenerator.CreateForECDsa(ecdsa)); } throw new InvalidOperationException( $"Had no handler for key of type {key?.GetType().FullName ?? "null"}"); }
public static void SelectCertificateSingleSelectionTest(int count) { using (ECDsa ecdsa = ECDsa.Create(EccTestData.Secp256r1Data.KeyParameters)) { CertificateRequest request = new CertificateRequest("CN=Test", ecdsa, HashAlgorithmName.SHA256); DateTimeOffset now = DateTimeOffset.UtcNow; using (X509Certificate2 cert = request.Create(request.SubjectName, X509SignatureGenerator.CreateForECDsa(ecdsa), now, now.AddMinutes(10), new byte[1])) { X509Certificate2Collection collection = new X509Certificate2Collection() { cert, cert }; X509Certificate2Collection actual = X509Certificate2UI.SelectFromCollection( collection, $"Choose {count} Certificate", string.Empty, count < 2 ? X509SelectionFlag.SingleSelection : X509SelectionFlag.MultiSelection, IntPtr.Zero); Assert.Equal(count, actual.Count); } } }
public void BasicEcdsaCertificateRequestTest() { // Load PKCS#11 based store using (var pkcs11Store = new Pkcs11X509Store(SoftHsm2Manager.LibraryPath, SoftHsm2Manager.PinProvider)) { // Find signing certificate (CA certificate) Pkcs11X509Certificate pkcs11CertOfCertificateAuthority = Helpers.GetCertificate(pkcs11Store, SoftHsm2Manager.Token1Label, SoftHsm2Manager.Token1TestUserEcdsaLabel); // Generate new key pair for end entity ECDsa ecKeyPairOfEndEntity = ECDsa.Create(ECCurve.NamedCurves.nistP256); // Define certificate request CertificateRequest certificateRequest = new CertificateRequest( new X500DistinguishedName("C=SK,L=Bratislava,CN=BasicEcdsaCertificateRequestTest"), ecKeyPairOfEndEntity, HashAlgorithmName.SHA256); // Define certificate extensions certificateRequest.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, true)); certificateRequest.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(certificateRequest.PublicKey, false)); certificateRequest.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature, false)); // Issue X.509 certificate for end entity X509Certificate2 certificateOfEndEntity = certificateRequest.Create( pkcs11CertOfCertificateAuthority.Info.ParsedCertificate.SubjectName, X509SignatureGenerator.CreateForECDsa(pkcs11CertOfCertificateAuthority.GetECDsaPrivateKey()), DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddDays(365), new BigInteger(1).ToByteArray()); // Verify signature on X.509 certificate for end entity Assert.IsTrue(CaCertSignedEndEntityCert(pkcs11CertOfCertificateAuthority.Info.ParsedCertificate.RawData, certificateOfEndEntity.RawData)); // Asociate end entity certificate with its private key certificateOfEndEntity = certificateOfEndEntity.CopyWithPrivateKey(ecKeyPairOfEndEntity); // Export end entity certificate to PKCS#12 file string basePath = Helpers.GetBasePath(); string pkcs12FilePath = Path.Combine(basePath, "BasicEcdsaCertificateRequestTest.p12"); File.WriteAllBytes(pkcs12FilePath, certificateOfEndEntity.Export(X509ContentType.Pkcs12, "password")); } }
public static void SerialNumber_AlwaysPositive(string desiredSerial, string expectedSerial) { using (ECDsa ecdsa = ECDsa.Create(EccTestData.Secp521r1_DiminishedPublic_Data.KeyParameters)) { var generator = X509SignatureGenerator.CreateForECDsa(ecdsa); CertificateRequest request = new CertificateRequest( new X500DistinguishedName("CN=Test Cert"), generator.PublicKey, HashAlgorithmName.SHA512); DateTimeOffset now = DateTimeOffset.UtcNow; byte[] serialNumber = desiredSerial.HexToByteArray(); // byte[] serialNumber X509Certificate2 cert = request.Create( request.SubjectName, generator, now, now.AddDays(1), serialNumber); using (cert) { Assert.Equal(expectedSerial, cert.SerialNumber); } // ReadOnlySpan<byte> serialNumber cert = request.Create( request.SubjectName, generator, now, now.AddDays(1), serialNumber.AsSpan()); using (cert) { Assert.Equal(expectedSerial, cert.SerialNumber); } } }
public static void NullAttributeInCollection() { using (ECDsa key = ECDsa.Create(EccTestData.Secp384r1Data.KeyParameters)) { CertificateRequest req = new CertificateRequest( "CN=Test", key, HashAlgorithmName.SHA384); req.OtherRequestAttributes.Add(null); X509SignatureGenerator gen = X509SignatureGenerator.CreateForECDsa(key); InvalidOperationException ex; ex = Assert.Throws <InvalidOperationException>(() => req.CreateSigningRequest()); Assert.Contains(nameof(CertificateRequest.OtherRequestAttributes), ex.Message); ex = Assert.Throws <InvalidOperationException>(() => req.CreateSigningRequest(gen)); Assert.Contains(nameof(CertificateRequest.OtherRequestAttributes), ex.Message); } }
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 }; Assert.Throws <ArgumentException>( () => 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)) { } } } }
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); }
static X509Certificate2 CreateBasicECDsaCertificateWithIssuerName( string subject, string issuer) { // Create the key for this certificate and initialize the keysiez var ecdsa = ECDsa.Create("ECDsa"); ecdsa.KeySize = 256; var hash = HashAlgorithmName.SHA256; var sigen = X509SignatureGenerator.CreateForECDsa(ecdsa); // Create the subject name for the new certificate var subjectName = new X500DistinguishedName(subject); // Create a certificate request - // this is codified form of the ASN certificate request format. var req = new CertificateRequest( subjectName, ecdsa, hash ); var issuerName = new X500DistinguishedName(issuer); X509Certificate2 cert = req.Create( issuerName, sigen, DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddYears(1), Guid.NewGuid().ToByteArray() ); cert = cert.CopyWithPrivateKey(ecdsa); return(cert); }
public static void ECDsaX509SignatureGeneratorCtor_Exceptions() { AssertExtensions.Throws <ArgumentNullException>( "key", () => X509SignatureGenerator.CreateForECDsa(null)); }