public override void ProcessServerCertificate(Certificate serverCertificate)
        {
            if (serverCertificate.IsEmpty)
                throw new TlsFatalAlert(AlertDescription.bad_certificate);

            X509CertificateStructure x509Cert = serverCertificate.GetCertificateAt(0);

            SubjectPublicKeyInfo keyInfo = x509Cert.SubjectPublicKeyInfo;
            try
            {
                this.mServerPublicKey = PublicKeyFactory.CreateKey(keyInfo);
            }
            catch (Exception e)
            {
                throw new TlsFatalAlert(AlertDescription.unsupported_certificate, e);
            }

            // Sanity check the PublicKeyFactory
            if (this.mServerPublicKey.IsPrivate)
                throw new TlsFatalAlert(AlertDescription.internal_error);

            this.mRsaServerPublicKey = ValidateRsaPublicKey((RsaKeyParameters)this.mServerPublicKey);

            TlsUtilities.ValidateKeyUsage(x509Cert, KeyUsage.KeyEncipherment);

            base.ProcessServerCertificate(serverCertificate);
        }
        public override void ProcessServerCertificate(Certificate serverCertificate)
        {
            if (mTlsSigner == null)
                throw new TlsFatalAlert(AlertDescription.unexpected_message);
            if (serverCertificate.IsEmpty)
                throw new TlsFatalAlert(AlertDescription.bad_certificate);

            X509CertificateStructure x509Cert = serverCertificate.GetCertificateAt(0);

            SubjectPublicKeyInfo keyInfo = x509Cert.SubjectPublicKeyInfo;
            try
            {
                this.mServerPublicKey = PublicKeyFactory.CreateKey(keyInfo);
            }
            catch (Exception e)
            {
                throw new TlsFatalAlert(AlertDescription.unsupported_certificate, e);
            }

            if (!mTlsSigner.IsValidPublicKey(this.mServerPublicKey))
                throw new TlsFatalAlert(AlertDescription.certificate_unknown);

            TlsUtilities.ValidateKeyUsage(x509Cert, KeyUsage.DigitalSignature);

            base.ProcessServerCertificate(serverCertificate);
        }
 public override bool VerifyRawSignature(SignatureAndHashAlgorithm algorithm, byte[] sigBytes,
     AsymmetricKeyParameter publicKey, byte[] hash)
 {
     ISigner signer = MakeSigner(algorithm, true, false, publicKey);
     signer.BlockUpdate(hash, 0, hash.Length);
     return signer.VerifySignature(sigBytes);
 }
		public bool VerifyRawSignature(byte[] sigBytes, AsymmetricKeyParameter publicKey, byte[] md5andsha1)
		{
			ISigner s = MakeSigner(new NullDigest(), false, publicKey);
			// Note: Only use the SHA1 part of the hash
			s.BlockUpdate(md5andsha1, 16, 20);
			return s.VerifySignature(sigBytes);
		}
		public virtual byte[] CalculateRawSignature(SecureRandom random,
			AsymmetricKeyParameter privateKey, byte[] md5andsha1)
		{
			ISigner s = MakeSigner(new NullDigest(), true, new ParametersWithRandom(privateKey, random));
			s.BlockUpdate(md5andsha1, 0, md5andsha1.Length);
			return s.GenerateSignature();
		}
Exemple #6
0
 public virtual byte[] GenerateRawSignature(SecureRandom random,
     AsymmetricKeyParameter privateKey, byte[] md5AndSha1)
 {
     IAsymmetricBlockCipher engine = CreateRsaImpl();
     engine.Init(true, new ParametersWithRandom(privateKey, random));
     return engine.ProcessBlock(md5AndSha1, 0, md5AndSha1.Length);
 }
        public DefaultTlsAgreementCredentials(Certificate certificate, AsymmetricKeyParameter privateKey)
        {
            if (certificate == null)
                throw new ArgumentNullException("certificate");
            if (certificate.IsEmpty)
                throw new ArgumentException("cannot be empty", "certificate");
            if (privateKey == null)
                throw new ArgumentNullException("privateKey");
            if (!privateKey.IsPrivate)
                throw new ArgumentException("must be private", "privateKey");

            if (privateKey is DHPrivateKeyParameters)
            {
                mBasicAgreement = new DHBasicAgreement();
                mTruncateAgreement = true;
            }
            else if (privateKey is ECPrivateKeyParameters)
            {
                mBasicAgreement = new ECDHBasicAgreement();
                mTruncateAgreement = false;
            }
            else
            {
                throw new ArgumentException("type not supported: " + privateKey.GetType().FullName, "privateKey");
            }

            this.mCertificate = certificate;
            this.mPrivateKey = privateKey;
        }
 public ScrambledKeyPair(AsymmetricCipherKeyPair pPair)
 {
     _pair = pPair;
     _publicKey = pPair.getPublic();
     _scrambledModulus = scrambleModulus((_publicKey as RSAKeyParameters).getModulus());
     _privateKey = pPair.getPrivate();
 }
		public virtual bool VerifyRawSignature(byte[] sigBytes, AsymmetricKeyParameter publicKey,
			byte[] md5andsha1)
		{
			ISigner s = MakeSigner(new NullDigest(), false, publicKey);
			s.BlockUpdate(md5andsha1, 0, md5andsha1.Length);
			return s.VerifySignature(sigBytes);
		}
Exemple #10
0
 public virtual bool VerifyRawSignature(byte[] sigBytes, AsymmetricKeyParameter publicKey,
     byte[] md5AndSha1)
 {
     IAsymmetricBlockCipher engine = CreateRsaImpl();
     engine.Init(false, publicKey);
     byte[] signed = engine.ProcessBlock(sigBytes, 0, sigBytes.Length);
     return Arrays.ConstantTimeAreEqual(signed, md5AndSha1);
 }
Exemple #11
0
 public virtual byte[] CalculateRawSignature(SecureRandom random,
     AsymmetricKeyParameter privateKey, byte[] md5andsha1)
 {
     ISigner sig = new GenericSigner(new Pkcs1Encoding(new RsaBlindedEngine()), new NullDigest());
     sig.Init(true, new ParametersWithRandom(privateKey, random));
     sig.BlockUpdate(md5andsha1, 0, md5andsha1.Length);
     return sig.GenerateSignature();
 }
		public virtual byte[] CalculateRawSignature(SecureRandom random,
			AsymmetricKeyParameter privateKey, byte[] md5andsha1)
		{
			ISigner s = MakeSigner(new NullDigest(), true, new ParametersWithRandom(privateKey, random));
			// Note: Only use the SHA1 part of the hash
			s.BlockUpdate(md5andsha1, 16, 20);
			return s.GenerateSignature();
		}
 public override byte[] GenerateRawSignature(SignatureAndHashAlgorithm algorithm,
     AsymmetricKeyParameter privateKey, byte[] hash)
 {
     ISigner signer = MakeSigner(algorithm, true, true,
         new ParametersWithRandom(privateKey, this.mContext.SecureRandom));
     signer.BlockUpdate(hash, 0, hash.Length);
     return signer.GenerateSignature();
 }
Exemple #14
0
		public byte[] CalculateRawSignature(AsymmetricKeyParameter privateKey, byte[] md5andsha1)
		{
			// Note: Only use the SHA1 part of the hash
			ISigner sig = new DsaDigestSigner(new DsaSigner(), new NullDigest());
			sig.Init(true, privateKey);
			sig.BlockUpdate(md5andsha1, 16, 20);
			return sig.GenerateSignature();
		}
        /// <exception cref="IOException"></exception>
        public override byte[] GenerateAgreement(AsymmetricKeyParameter peerPublicKey)
        {
            mBasicAgreement.Init(mPrivateKey);
            BigInteger agreementValue = mBasicAgreement.CalculateAgreement(peerPublicKey);

            if (mTruncateAgreement)
            {
                return BigIntegers.AsUnsignedByteArray(agreementValue);
            }

            return BigIntegers.AsUnsignedByteArray(mBasicAgreement.GetFieldSize(), agreementValue);
        }
        public virtual byte[] GenerateAgreement(AsymmetricKeyParameter serverPublicKey)
        {
            basicAgreement.Init(clientPrivateKey);
            BigInteger agreementValue = basicAgreement.CalculateAgreement(serverPublicKey);

            if (truncateAgreement)
            {
                return BigIntegers.AsUnsignedByteArray(agreementValue);
            }

            return BigIntegers.AsUnsignedByteArray(basicAgreement.GetFieldSize(), agreementValue);
        }
Exemple #17
0
 public override bool VerifyRawSignature(SignatureAndHashAlgorithm algorithm, byte[] sigBytes,
     AsymmetricKeyParameter publicKey, byte[] hash)
 {
     ISigner signer = MakeSigner(algorithm, true, false, publicKey);
     if (algorithm == null)
     {
         // Note: Only use the SHA1 part of the (MD5/SHA1) hash
         signer.BlockUpdate(hash, 16, 20);
     }
     else
     {
         signer.BlockUpdate(hash, 0, hash.Length);
     }
     return signer.VerifySignature(sigBytes);
 }
Exemple #18
0
 public override byte[] GenerateRawSignature(SignatureAndHashAlgorithm algorithm,
     AsymmetricKeyParameter privateKey, byte[] hash)
 {
     ISigner signer = MakeSigner(algorithm, true, true,
         new ParametersWithRandom(privateKey, this.mContext.SecureRandom));
     if (algorithm == null)
     {
         // Note: Only use the SHA1 part of the (MD5/SHA1) hash
         signer.BlockUpdate(hash, 16, 20);
     }
     else
     {
         signer.BlockUpdate(hash, 0, hash.Length);
     }
     return signer.GenerateSignature();
 }
        public virtual void ProcessServerCertificate(Certificate serverCertificate)
        {
            X509CertificateStructure x509Cert = serverCertificate.GetCertificateAt(0);
            SubjectPublicKeyInfo keyInfo = x509Cert.SubjectPublicKeyInfo;

            try
            {
                this.serverPublicKey = PublicKeyFactory.CreateKey(keyInfo);
            }
            catch (Exception)
            {
                throw new TlsFatalAlert(AlertDescription.unsupported_certificate);
            }

            if (tlsSigner == null)
            {
                try
                {
                    this.ecAgreeServerPublicKey = ValidateECPublicKey((ECPublicKeyParameters)this.serverPublicKey);
                }
                catch (InvalidCastException)
                {
                    throw new TlsFatalAlert(AlertDescription.certificate_unknown);
                }

                TlsUtilities.ValidateKeyUsage(x509Cert, KeyUsage.KeyAgreement);
            }
            else
            {
                if (!tlsSigner.IsValidPublicKey(this.serverPublicKey))
                {
                    throw new TlsFatalAlert(AlertDescription.certificate_unknown);
                }

                TlsUtilities.ValidateKeyUsage(x509Cert, KeyUsage.DigitalSignature);
            }
            
            // TODO
            /*
            * Perform various checks per RFC2246 7.4.2: "Unless otherwise specified, the
            * signing algorithm for the certificate must be the same as the algorithm for the
            * certificate key."
            */
        }
        public override void ProcessServerCertificate(Certificate serverCertificate)
        {
            if (serverCertificate.IsEmpty)
                throw new TlsFatalAlert(AlertDescription.bad_certificate);

            X509CertificateStructure x509Cert = serverCertificate.GetCertificateAt(0);

            SubjectPublicKeyInfo keyInfo = x509Cert.SubjectPublicKeyInfo;
            try
            {
                this.mServerPublicKey = PublicKeyFactory.CreateKey(keyInfo);
            }
            catch (Exception e)
            {
                throw new TlsFatalAlert(AlertDescription.unsupported_certificate, e);
            }

            if (mTlsSigner == null)
            {
                try
                {
                    this.mDHAgreePublicKey = TlsDHUtilities.ValidateDHPublicKey((DHPublicKeyParameters)this.mServerPublicKey);
                    this.mDHParameters = ValidateDHParameters(mDHAgreePublicKey.Parameters);
                }
                catch (InvalidCastException e)
                {
                    throw new TlsFatalAlert(AlertDescription.certificate_unknown, e);
                }

                TlsUtilities.ValidateKeyUsage(x509Cert, KeyUsage.KeyAgreement);
            }
            else
            {
                if (!mTlsSigner.IsValidPublicKey(this.mServerPublicKey))
                {
                    throw new TlsFatalAlert(AlertDescription.certificate_unknown);
                }

                TlsUtilities.ValidateKeyUsage(x509Cert, KeyUsage.DigitalSignature);
            }

            base.ProcessServerCertificate(serverCertificate);
        }
        public DefaultTlsSignerCredentials(TlsClientContext context,
            Certificate clientCertificate, AsymmetricKeyParameter clientPrivateKey)
        {
            if (clientCertificate == null)
            {
                throw new ArgumentNullException("clientCertificate");
            }
            if (clientCertificate.Length == 0)
            {
                throw new ArgumentException("cannot be empty", "clientCertificate");
            }
            if (clientPrivateKey == null)
            {
                throw new ArgumentNullException("clientPrivateKey");
            }
            if (!clientPrivateKey.IsPrivate)
            {
                throw new ArgumentException("must be private", "clientPrivateKey");
            }

            if (clientPrivateKey is RsaKeyParameters)
            {
                clientSigner = new TlsRsaSigner();
            }
            else if (clientPrivateKey is DsaPrivateKeyParameters)
            {
                clientSigner = new TlsDssSigner();
            }
            else if (clientPrivateKey is ECPrivateKeyParameters)
            {
                clientSigner = new TlsECDsaSigner();
            }
            else
            {
                throw new ArgumentException("type not supported: "
                    + clientPrivateKey.GetType().FullName, "clientPrivateKey");
            }

            this.context = context;
            this.clientCert = clientCertificate;
            this.clientPrivateKey = clientPrivateKey;
        }
        public DefaultTlsSignerCredentials(TlsContext context, Certificate certificate, AsymmetricKeyParameter privateKey,
            SignatureAndHashAlgorithm signatureAndHashAlgorithm)
        {
            if (certificate == null)
                throw new ArgumentNullException("certificate");
            if (certificate.IsEmpty)
                throw new ArgumentException("cannot be empty", "clientCertificate");
            if (privateKey == null)
                throw new ArgumentNullException("privateKey");
            if (!privateKey.IsPrivate)
                throw new ArgumentException("must be private", "privateKey");
            if (TlsUtilities.IsTlsV12(context) && signatureAndHashAlgorithm == null)
                throw new ArgumentException("cannot be null for (D)TLS 1.2+", "signatureAndHashAlgorithm");

            if (privateKey is RsaKeyParameters)
            {
                mSigner = new TlsRsaSigner();
            }
            else if (privateKey is DsaPrivateKeyParameters)
            {
                mSigner = new TlsDssSigner();
            }
            else if (privateKey is ECPrivateKeyParameters)
            {
                mSigner = new TlsECDsaSigner();
            }
            else
            {
                throw new ArgumentException("type not supported: " + privateKey.GetType().FullName, "privateKey");
            }

            this.mSigner.Init(context);

            this.mContext = context;
            this.mCertificate = certificate;
            this.mPrivateKey = privateKey;
            this.mSignatureAndHashAlgorithm = signatureAndHashAlgorithm;
        }
        public DefaultTlsAgreementCredentials(Certificate clientCertificate, AsymmetricKeyParameter clientPrivateKey)
        {
            if (clientCertificate == null)
            {
                throw new ArgumentNullException("clientCertificate");
            }
            if (clientCertificate.Length == 0)
            {
                throw new ArgumentException("cannot be empty", "clientCertificate");
            }
            if (clientPrivateKey == null)
            {
                throw new ArgumentNullException("clientPrivateKey");
            }
            if (!clientPrivateKey.IsPrivate)
            {
                throw new ArgumentException("must be private", "clientPrivateKey");
            }

            if (clientPrivateKey is DHPrivateKeyParameters)
            {
                basicAgreement = new DHBasicAgreement();
                truncateAgreement = true;
            }
            else if (clientPrivateKey is ECPrivateKeyParameters)
            {
                basicAgreement = new ECDHBasicAgreement();
                truncateAgreement = false;
            }
            else
            {
                throw new ArgumentException("type not supported: "
                    + clientPrivateKey.GetType().FullName, "clientPrivateKey");
            }

            this.clientCert = clientCertificate;
            this.clientPrivateKey = clientPrivateKey;
        }
        public virtual void ProcessServerCertificate(Certificate serverCertificate)
		{
            if (keyExchange != KeyExchangeAlgorithm.RSA_PSK)
            {
                throw new TlsFatalAlert(AlertDescription.unexpected_message);
            }

            X509CertificateStructure x509Cert = serverCertificate.certs[0];
            SubjectPublicKeyInfo keyInfo = x509Cert.SubjectPublicKeyInfo;

            try
            {
                this.serverPublicKey = PublicKeyFactory.CreateKey(keyInfo);
            }
            //			catch (RuntimeException)
            catch (Exception)
            {
                throw new TlsFatalAlert(AlertDescription.unsupported_certificate);
            }

            // Sanity check the PublicKeyFactory
            if (this.serverPublicKey.IsPrivate)
            {
                throw new TlsFatalAlert(AlertDescription.internal_error);
            }

            this.rsaServerPublicKey = ValidateRsaPublicKey((RsaKeyParameters)this.serverPublicKey);

            TlsUtilities.ValidateKeyUsage(x509Cert, KeyUsage.KeyEncipherment);

            // TODO
            /*
            * Perform various checks per RFC2246 7.4.2: "Unless otherwise specified, the
            * signing algorithm for the certificate must be the same as the algorithm for the
            * certificate key."
            */
        }
        public DefaultTlsEncryptionCredentials(TlsContext context, Certificate certificate,
            AsymmetricKeyParameter privateKey)
        {
            if (certificate == null)
                throw new ArgumentNullException("certificate");
            if (certificate.IsEmpty)
                throw new ArgumentException("cannot be empty", "certificate");
            if (privateKey == null)
                throw new ArgumentNullException("'privateKey' cannot be null");
            if (!privateKey.IsPrivate)
                throw new ArgumentException("must be private", "privateKey");

            if (privateKey is RsaKeyParameters)
            {
            }
            else
            {
                throw new ArgumentException("type not supported: " + Platform.GetTypeName(privateKey), "privateKey");
            }

            this.mContext = context;
            this.mCertificate = certificate;
            this.mPrivateKey = privateKey;
        }
Exemple #26
0
 public AsymmetricKeyEntry(
     AsymmetricKeyParameter key,
     Hashtable attributes) : base(attributes)
 {
     this.key = key;
 }
Exemple #27
0
 public AsymmetricKeyEntry(
     AsymmetricKeyParameter key) : base(new Hashtable())
 {
     this.key = key;
 }
Exemple #28
0
 public virtual void Verify(
     AsymmetricKeyParameter publicKey)
 {
     Verify(new Asn1SignatureVerifierProvider(publicKey));
 }
 public override ISigner CreateSigner(SignatureAndHashAlgorithm algorithm, AsymmetricKeyParameter privateKey)
 {
     return(MakeSigner(algorithm, false, true, new ParametersWithRandom(privateKey, this.mContext.SecureRandom)));
 }
Exemple #30
0
        public static void SignByCertInfo(Dictionary <string, string> reqData, string certId, AsymmetricKeyParameter parameters)
        {
            if (!reqData.ContainsKey("signMethod"))
            {
                throw new Exception("signMethod must Not null");
            }
            var signMethod = reqData["signMethod"];

            if (!reqData.ContainsKey("version"))
            {
                throw new Exception("version must Not null");
            }
            var version = reqData["version"];

            if ("01".Equals(signMethod))
            {
                reqData["certId"] = certId;

                var stringData       = GetSignContent(reqData, true, false);
                var stringSignDigest = SHA256.Compute(stringData);

                var stringSign = SignSha256WithRsa(stringSignDigest, parameters);

                //设置签名域值
                reqData["signature"] = stringSign;
            }
            else
            {
                throw new Exception("Error signMethod [" + signMethod + "] in SignByCertInfo. ");
            }
        }
Exemple #31
0
        private bool VerifyDigest(
            byte[]                                  digest,
            AsymmetricKeyParameter key,
            byte[]                                  signature)
        {
            string algorithm = Helper.GetEncryptionAlgName(this.EncryptionAlgOid);

            try
            {
                if (algorithm.Equals("RSA"))
                {
                    IBufferedCipher c = CipherUtilities.GetCipher("RSA//PKCS1Padding");

                    c.Init(false, key);

                    byte[] decrypt = c.DoFinal(signature);

                    DigestInfo digInfo = DerDecode(decrypt);

                    if (!digInfo.AlgorithmID.ObjectID.Equals(digestAlgorithm.ObjectID))
                    {
                        return(false);
                    }

                    if (!IsNull(digInfo.AlgorithmID.Parameters))
                    {
                        return(false);
                    }

                    byte[] sigHash = digInfo.GetDigest();

                    return(Arrays.ConstantTimeAreEqual(digest, sigHash));
                }
                else if (algorithm.Equals("DSA"))
                {
                    ISigner sig = SignerUtilities.GetSigner("NONEwithDSA");

                    sig.Init(false, key);

                    sig.BlockUpdate(digest, 0, digest.Length);

                    return(sig.VerifySignature(signature));
                }
                else
                {
                    throw new CmsException("algorithm: " + algorithm + " not supported in base signatures.");
                }
            }
            catch (SecurityUtilityException e)
            {
                throw e;
            }
            catch (GeneralSecurityException e)
            {
                throw new CmsException("Exception processing signature: " + e, e);
            }
            catch (IOException e)
            {
                throw new CmsException("Exception decoding signature: " + e, e);
            }
        }
Exemple #32
0
        private void extensionTest(AsymmetricKeyParameter privateKey, X509Certificate cert, IX509Store certs)
        {
            TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator(
                privateKey, cert, TspAlgorithms.Sha1, "1.2");

            tsTokenGen.SetCertificates(certs);

            TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator();

            // --- These are test case only values
            reqGen.SetReqPolicy("2.5.29.56");
            reqGen.AddExtension(new DerObjectIdentifier("1.3.6.1.5.5.7.1.2"), true, new DerOctetString(new byte[20]));
            // --- not for any real world purpose.

            TimeStampRequest request = reqGen.Generate(TspAlgorithms.Sha1, new byte[20]);

            try
            {
                request.Validate(new ArrayList(), new ArrayList(), new ArrayList());
                Assert.Fail("expected exception");
            } catch (Exception ex)
            {
                Assert.True("request contains unknown algorithm" == ex.Message);
            }

            ArrayList algorithms = new ArrayList();

            algorithms.Add(TspAlgorithms.Sha1);

            try
            {
                request.Validate(algorithms, new ArrayList(), new ArrayList());
                Assert.Fail("no exception");
            }
            catch (Exception e)
            {
                Assert.IsTrue(e.Message == "request contains unknown policy");
            }

            ArrayList policies = new ArrayList();

            // Testing only do not use in real world.
            policies.Add("2.5.29.56");

            try
            {
                request.Validate(algorithms, policies, new ArrayList());
                Assert.Fail("no exception");
            }
            catch (Exception e)
            {
                Assert.IsTrue(e.Message == "request contains unknown extension");
            }

            ArrayList extensions = new ArrayList();

            // Testing only do not use in real world/
            extensions.Add("1.3.6.1.5.5.7.1.2");


            // should validate with full set
            request.Validate(algorithms, policies, extensions);

            // should validate with null policy
            request.Validate(algorithms, null, extensions);

            TimeStampResponseGenerator tsRespGen = new TimeStampResponseGenerator(tsTokenGen, TspAlgorithms.Allowed);

            TimeStampResponse tsResp = tsRespGen.Generate(request, new BigInteger("23"), DateTime.UtcNow);

            tsResp = new TimeStampResponse(tsResp.GetEncoded());

            TimeStampToken tsToken = tsResp.TimeStampToken;

            tsToken.Validate(cert);

            Asn1.Cms.AttributeTable table = tsToken.SignedAttributes;

            Assert.NotNull(table[PkcsObjectIdentifiers.IdAASigningCertificate], "no signingCertificate attribute found");
        }
Exemple #33
0
        private static byte[] SerializePublicKey(AsymmetricKeyParameter publicKey)
        {
            SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);

            return(SerializeKey(publicKeyInfo));
        }
Exemple #34
0
        public void doTestECGost(
            string name)
        {
//			ECGenParameterSpec ecSpec = new ECGenParameterSpec(name);
            ECDomainParameters ecSpec = GetCurveParameters(name);

            IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("ECGOST3410");

//			g.initialize(ecSpec, new SecureRandom());
            g.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom()));

            ISigner sgr = SignerUtilities.GetSigner("ECGOST3410");
            AsymmetricCipherKeyPair pair = g.GenerateKeyPair();
            AsymmetricKeyParameter  sKey = pair.Private;
            AsymmetricKeyParameter  vKey = pair.Public;

            sgr.Init(true, sKey);

            byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' };

            sgr.BlockUpdate(message, 0, message.Length);

            byte[] sigBytes = sgr.GenerateSignature();

            sgr.Init(false, vKey);

            sgr.BlockUpdate(message, 0, message.Length);

            if (!sgr.VerifySignature(sigBytes))
            {
                Fail(name + " verification failed");
            }

            // TODO Get this working?
//			//
//			// public key encoding test
//			//
////			byte[]              pubEnc = vKey.getEncoded();
//			byte[] pubEnc = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(vKey).GetDerEncoded();
//
////			KeyFactory          keyFac = KeyFactory.getInstance("ECGOST3410");
////			X509EncodedKeySpec  pubX509 = new X509EncodedKeySpec(pubEnc);
////			ECPublicKey         pubKey = (ECPublicKey)keyFac.generatePublic(pubX509);
//			ECPublicKeyParameters pubKey = (ECPublicKeyParameters) PublicKeyFactory.CreateKey(pubEnc);
//
////			if (!pubKey.getW().equals(((ECPublicKey)vKey).getW()))
//			if (!pubKey.Q.Equals(((ECPublicKeyParameters)vKey).Q))
//			{
//				Fail("public key encoding (Q test) failed");
//			}

            // TODO Put back in?
//			if (!(pubKey.Parameters is ECNamedCurveSpec))
//			{
//				Fail("public key encoding not named curve");
//			}

            // TODO Get this working?
//			//
//			// private key encoding test
//			//
////			byte[]              privEnc = sKey.getEncoded();
//			byte[] privEnc = PrivateKeyInfoFactory.CreatePrivateKeyInfo(sKey).GetDerEncoded();
//
////			PKCS8EncodedKeySpec privPKCS8 = new PKCS8EncodedKeySpec(privEnc);
////			ECPrivateKey        privKey = (ECPrivateKey)keyFac.generatePrivate(privPKCS8);
//			ECPrivateKeyParameters privKey = (ECPrivateKeyParameters) PrivateKeyFactory.CreateKey(privEnc);
//
////			if (!privKey.getS().Equals(((ECPrivateKey)sKey).getS()))
//			if (!privKey.D.Equals(((ECPrivateKeyParameters)sKey).D))
//			{
//				Fail("GOST private key encoding (D test) failed");
//			}

            // TODO Put back in?
//			if (!(privKey.Parameters is ECNamedCurveSpec))
//			{
//				Fail("GOST private key encoding not named curve");
//			}
//
//			ECNamedCurveSpec privSpec = (ECNamedCurveSpec)privKey.getParams();
//			if (!privSpec.getName().equalsIgnoreCase(name)
//				&& !privSpec.getName().equalsIgnoreCase((String)CURVE_ALIASES[name]))
//			{
//				Fail("GOST private key encoding wrong named curve. Expected: " + name + " got " + privSpec.getName());
//			}
        }
Exemple #35
0
        private void responseValidationTest(AsymmetricKeyParameter privateKey, X509Certificate cert, IX509Store certs)
        {
            TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator(
                privateKey, cert, TspAlgorithms.MD5, "1.2");

            tsTokenGen.SetCertificates(certs);


            TimeStampRequestGenerator reqGen  = new TimeStampRequestGenerator();
            TimeStampRequest          request = reqGen.Generate(TspAlgorithms.Sha1, new byte[20], BigInteger.ValueOf(100));

            TimeStampResponseGenerator tsRespGen = new TimeStampResponseGenerator(tsTokenGen, TspAlgorithms.Allowed);

            TimeStampResponse tsResp = tsRespGen.Generate(request, BigInteger.ValueOf(23), DateTime.UtcNow);

            tsResp = new TimeStampResponse(tsResp.GetEncoded());

            TimeStampToken tsToken = tsResp.TimeStampToken;

            tsToken.Validate(cert);


            try
            {
                request = reqGen.Generate(TspAlgorithms.Sha1, new byte[20], BigInteger.ValueOf(101));

                tsResp.Validate(request);

                Assert.Fail("response validation failed on invalid nonce.");
            }
            catch (TspValidationException e)
            {
                // ignore
            }

            try
            {
                request = reqGen.Generate(TspAlgorithms.Sha1, new byte[22], BigInteger.ValueOf(100));

                tsResp.Validate(request);

                Assert.Fail("response validation failed on wrong digest.");
            }
            catch (TspValidationException e)
            {
                // ignore
            }

            try
            {
                request = reqGen.Generate(TspAlgorithms.MD5, new byte[20], BigInteger.ValueOf(100));

                tsResp.Validate(request);

                Assert.Fail("response validation failed on wrong digest.");
            }
            catch (TspValidationException e)
            {
                // ignore
            }
        }
		public abstract bool IsValidPublicKey(AsymmetricKeyParameter publicKey);
Exemple #37
0
        internal string GetEncOid(
            AsymmetricKeyParameter key,
            string digestOID)
        {
            string encOID = null;

            if (key is RsaKeyParameters)
            {
                if (!((RsaKeyParameters)key).IsPrivate)
                {
                    throw new ArgumentException("Expected RSA private key");
                }

                encOID = CmsSignedGenerator.EncryptionRsa;
            }
            else if (key is DsaPrivateKeyParameters)
            {
                if (digestOID.Equals(CmsSignedGenerator.DigestSha1))
                {
                    encOID = CmsSignedGenerator.EncryptionDsa;
                }
                else if (digestOID.Equals(CmsSignedGenerator.DigestSha224))
                {
                    encOID = NistObjectIdentifiers.DsaWithSha224.Id;
                }
                else if (digestOID.Equals(CmsSignedGenerator.DigestSha256))
                {
                    encOID = NistObjectIdentifiers.DsaWithSha256.Id;
                }
                else if (digestOID.Equals(CmsSignedGenerator.DigestSha384))
                {
                    encOID = NistObjectIdentifiers.DsaWithSha384.Id;
                }
                else if (digestOID.Equals(CmsSignedGenerator.DigestSha512))
                {
                    encOID = NistObjectIdentifiers.DsaWithSha512.Id;
                }
                else
                {
                    throw new ArgumentException("can't mix DSA with anything but SHA1/SHA2");
                }
            }
            else if (key is ECPrivateKeyParameters)
            {
                ECPrivateKeyParameters ecPrivKey = (ECPrivateKeyParameters)key;
                string algName = ecPrivKey.AlgorithmName;

                if (algName == "ECGOST3410")
                {
                    encOID = CmsSignedGenerator.EncryptionECGost3410;
                }
                else
                {
                    // TODO Should we insist on algName being one of "EC" or "ECDSA", as Java does?
                    encOID = (string)ecAlgorithms[digestOID];

                    if (encOID == null)
                    {
                        throw new ArgumentException("can't mix ECDSA with anything but SHA family digests");
                    }
                }
            }
            else if (key is Gost3410PrivateKeyParameters)
            {
                encOID = CmsSignedGenerator.EncryptionGost3410;
            }
            else
            {
                throw new ArgumentException("Unknown algorithm in CmsSignedGenerator.GetEncOid");
            }

            return(encOID);
        }
Exemple #38
0
        private void overrideAttrsTest(AsymmetricKeyParameter privateKey, X509Certificate cert, IX509Store certs)
        {
            SignerInfoGeneratorBuilder signerInfoGenBuilder = new SignerInfoGeneratorBuilder();

            IssuerSerial issuerSerial = new IssuerSerial(
                new GeneralNames(
                    new GeneralName(
                        X509CertificateStructure.GetInstance(cert.GetEncoded()).Issuer)),
                new DerInteger(cert.SerialNumber));

            byte[] certHash256;
            byte[] certHash;

            {
                Asn1DigestFactory digCalc = Asn1DigestFactory.Get(OiwObjectIdentifiers.IdSha1);
                IStreamCalculator calc    = digCalc.CreateCalculator();
                using (Stream s = calc.Stream)
                {
                    var crt = cert.GetEncoded();
                    s.Write(crt, 0, crt.Length);
                }

                certHash = ((SimpleBlockResult)calc.GetResult()).Collect();
            }


            {
                Asn1DigestFactory digCalc = Asn1DigestFactory.Get(NistObjectIdentifiers.IdSha256);
                IStreamCalculator calc    = digCalc.CreateCalculator();
                using (Stream s = calc.Stream)
                {
                    var crt = cert.GetEncoded();
                    s.Write(crt, 0, crt.Length);
                }

                certHash256 = ((SimpleBlockResult)calc.GetResult()).Collect();
            }


            EssCertID   essCertid   = new EssCertID(certHash, issuerSerial);
            EssCertIDv2 essCertidV2 = new EssCertIDv2(certHash256, issuerSerial);

            signerInfoGenBuilder.WithSignedAttributeGenerator(new TestAttrGen()
            {
                EssCertID   = essCertid,
                EssCertIDv2 = essCertidV2
            });


            Asn1SignatureFactory sigfact = new Asn1SignatureFactory("SHA1WithRSA", privateKey);
            SignerInfoGenerator
                signerInfoGenerator = signerInfoGenBuilder.Build(sigfact, cert);

            TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator(
                signerInfoGenerator,
                Asn1DigestFactory.Get(OiwObjectIdentifiers.IdSha1), new DerObjectIdentifier("1.2"), true);


            tsTokenGen.SetCertificates(certs);


            TimeStampRequestGenerator reqGen  = new TimeStampRequestGenerator();
            TimeStampRequest          request = reqGen.Generate(TspAlgorithms.Sha1, new byte[20], BigInteger.ValueOf(100));

            TimeStampResponseGenerator tsRespGen = new TimeStampResponseGenerator(tsTokenGen, TspAlgorithms.Allowed);

            TimeStampResponse tsResp = tsRespGen.Generate(request, BigInteger.ValueOf(23), DateTime.UtcNow);

            tsResp = new TimeStampResponse(tsResp.GetEncoded());

            TimeStampToken tsToken = tsResp.TimeStampToken;

            tsToken.Validate(cert);

            Asn1.Cms.AttributeTable table = tsToken.SignedAttributes;

            Assert.NotNull(table[PkcsObjectIdentifiers.IdAASigningCertificate], "no signingCertificate attribute found");
            Assert.NotNull(table[PkcsObjectIdentifiers.IdAASigningCertificateV2], "no signingCertificateV2 attribute found");

            SigningCertificate sigCert = SigningCertificate.GetInstance(table[PkcsObjectIdentifiers.IdAASigningCertificate].AttrValues[0]);

            Assert.IsTrue(cert.CertificateStructure.Issuer.Equals(sigCert.GetCerts()[0].IssuerSerial.Issuer.GetNames()[0].Name));
            Assert.IsTrue(cert.CertificateStructure.SerialNumber.Value.Equals(sigCert.GetCerts()[0].IssuerSerial.Serial.Value));
            Assert.IsTrue(Arrays.AreEqual(certHash, sigCert.GetCerts()[0].GetCertHash()));

            SigningCertificate sigCertV2 = SigningCertificate.GetInstance(table[PkcsObjectIdentifiers.IdAASigningCertificateV2].AttrValues[0]);

            Assert.IsTrue(cert.CertificateStructure.Issuer.Equals(sigCertV2.GetCerts()[0].IssuerSerial.Issuer.GetNames()[0].Name));
            Assert.IsTrue(cert.CertificateStructure.SerialNumber.Value.Equals(sigCertV2.GetCerts()[0].IssuerSerial.Serial.Value));
            Assert.IsTrue(Arrays.AreEqual(certHash256, sigCertV2.GetCerts()[0].GetCertHash()));
        }
Exemple #39
0
 public static bool Verify(string data, string signature, AsymmetricKeyParameter pubKey)
 {
     return(VerifyBytes(data, Convert.FromBase64String(signature), pubKey));
 }
 /// <summary>Generate an X509 CRL, based on the current issuer and subject.</summary>
 /// <param name="privateKey">The key used for signing.</param>
 public X509Crl Generate(
     AsymmetricKeyParameter privateKey)
 {
     return(Generate(privateKey, null));
 }
Exemple #41
0
 public static string Sign(string data, AsymmetricKeyParameter privKey)
 {
     return(Convert.ToBase64String(SignBytes(data, privKey)));
 }
        /// <summary>
        /// Generates the certificate.
        /// </summary>
        /// <param name="subjectName">Name of the subject.</param>
        /// <param name="issuerName">Name of the issuer.</param>
        /// <param name="validFrom">The valid from.</param>
        /// <param name="validTo">The valid to.</param>
        /// <param name="keyStrength">The key strength.</param>
        /// <param name="signatureAlgorithm">The signature algorithm.</param>
        /// <param name="issuerPrivateKey">The issuer private key.</param>
        /// <param name="hostName">The host name</param>
        /// <returns>X509Certificate2 instance.</returns>
        /// <exception cref="PemException">Malformed sequence in RSA private key</exception>
        private static X509Certificate2 GenerateCertificate(string hostName,
                                                            string subjectName,
                                                            string issuerName, DateTime validFrom,
                                                            DateTime validTo, int keyStrength       = 2048,
                                                            string signatureAlgorithm               = "SHA256WithRSA",
                                                            AsymmetricKeyParameter issuerPrivateKey = null)
        {
            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var secureRandom    = new SecureRandom(randomGenerator);

            // The Certificate Generator
            var certificateGenerator = new X509V3CertificateGenerator();

            // Serial Number
            var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), secureRandom);

            certificateGenerator.SetSerialNumber(serialNumber);

            // Issuer and Subject Name
            var subjectDn = new X509Name(subjectName);
            var issuerDn  = new X509Name(issuerName);

            certificateGenerator.SetIssuerDN(issuerDn);
            certificateGenerator.SetSubjectDN(subjectDn);

            certificateGenerator.SetNotBefore(validFrom);
            certificateGenerator.SetNotAfter(validTo);

            if (hostName != null)
            {
                //add subject alternative names
                var subjectAlternativeNames = new Asn1Encodable[]
                {
                    new GeneralName(GeneralName.DnsName, hostName),
                };

                var subjectAlternativeNamesExtension = new DerSequence(subjectAlternativeNames);
                certificateGenerator.AddExtension(
                    X509Extensions.SubjectAlternativeName.Id, false, subjectAlternativeNamesExtension);
            }
            // Subject Public Key
            var keyGenerationParameters = new KeyGenerationParameters(secureRandom, keyStrength);
            var keyPairGenerator        = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            var subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // Set certificate intended purposes to only Server Authentication
            certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage.Id, false, new ExtendedKeyUsage(KeyPurposeID.IdKPServerAuth));

            var signatureFactory = new Asn1SignatureFactory(signatureAlgorithm, issuerPrivateKey ?? subjectKeyPair.Private, secureRandom);

            // Self-sign the certificate
            var certificate     = certificateGenerator.Generate(signatureFactory);
            var x509Certificate = new X509Certificate2(certificate.GetEncoded());

            // Corresponding private key
            var privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);

            var seq = (Asn1Sequence)Asn1Object.FromByteArray(privateKeyInfo.ParsePrivateKey().GetDerEncoded());

            if (seq.Count != 9)
            {
                throw new PemException("Malformed sequence in RSA private key");
            }

            var rsa       = RsaPrivateKeyStructure.GetInstance(seq);
            var rsaparams = new RsaPrivateCrtKeyParameters(rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient);

            // Set private key onto certificate instance
            x509Certificate.PrivateKey   = DotNetUtilities.ToRSA(rsaparams);
            x509Certificate.FriendlyName = subjectName;

            return(x509Certificate);
        }
		/// <summary>
		/// Generate a new X509Certificate.
		/// </summary>
		/// <param name="privateKey">The private key of the issuer used to sign this certificate.</param>
		/// <returns>An X509Certificate.</returns>

		public X509Certificate Generate(
			AsymmetricKeyParameter privateKey)
		{
			return Generate(privateKey, null);
		}
 public TimeStampTokenGenerator(AsymmetricKeyParameter key, X509Certificate cert, string digestOID, string tsaPolicyOID)
     : this(key, cert, digestOID, tsaPolicyOID, null, null)
 {
 }
Exemple #45
0
        public static string EncryptData(string dataString, AsymmetricKeyParameter key)
        {
            var data = EncryptData(Encoding.UTF8.GetBytes(dataString), key);

            return(Convert.ToBase64String(data));
        }
Exemple #46
0
 public AsymmetricKeyEntry(
     AsymmetricKeyParameter key)
     : base(Platform.CreateHashtable())
 {
     this.key = key;
 }
Exemple #47
0
        private bool DoVerify(
            AsymmetricKeyParameter key)
        {
            string  digestName = Helper.GetDigestAlgName(this.DigestAlgOid);
            IDigest digest     = Helper.GetDigestInstance(digestName);

            DerObjectIdentifier sigAlgOid = this.encryptionAlgorithm.ObjectID;
            Asn1Encodable       sigParams = this.encryptionAlgorithm.Parameters;
            ISigner             sig;

            if (sigAlgOid.Equals(Asn1.Pkcs.PkcsObjectIdentifiers.IdRsassaPss))
            {
                // RFC 4056 2.2
                // When the id-RSASSA-PSS algorithm identifier is used for a signature,
                // the AlgorithmIdentifier parameters field MUST contain RSASSA-PSS-params.
                if (sigParams == null)
                {
                    throw new CmsException("RSASSA-PSS signature must specify algorithm parameters");
                }

                try
                {
                    // TODO Provide abstract configuration mechanism
                    // (via alternate SignerUtilities.GetSigner method taking ASN.1 params)

                    Asn1.Pkcs.RsassaPssParameters pss = Asn1.Pkcs.RsassaPssParameters.GetInstance(
                        sigParams.ToAsn1Object());

                    if (!pss.HashAlgorithm.ObjectID.Equals(this.digestAlgorithm.ObjectID))
                    {
                        throw new CmsException("RSASSA-PSS signature parameters specified incorrect hash algorithm");
                    }
                    if (!pss.MaskGenAlgorithm.ObjectID.Equals(Asn1.Pkcs.PkcsObjectIdentifiers.IdMgf1))
                    {
                        throw new CmsException("RSASSA-PSS signature parameters specified unknown MGF");
                    }

                    IDigest pssDigest    = DigestUtilities.GetDigest(pss.HashAlgorithm.ObjectID);
                    int     saltLength   = pss.SaltLength.Value.IntValue;
                    byte    trailerField = (byte)pss.TrailerField.Value.IntValue;

                    // RFC 4055 3.1
                    // The value MUST be 1, which represents the trailer field with hexadecimal value 0xBC
                    if (trailerField != 1)
                    {
                        throw new CmsException("RSASSA-PSS signature parameters must have trailerField of 1");
                    }

                    sig = new PssSigner(new RsaBlindedEngine(), pssDigest, saltLength);
                }
                catch (Exception e)
                {
                    throw new CmsException("failed to set RSASSA-PSS signature parameters", e);
                }
            }
            else
            {
                // TODO Probably too strong a check at the moment
//				if (sigParams != null)
//					throw new CmsException("unrecognised signature parameters provided");

                string signatureName = digestName + "with" + Helper.GetEncryptionAlgName(this.EncryptionAlgOid);

                sig = Helper.GetSignatureInstance(signatureName);
            }

            try
            {
                if (digestCalculator != null)
                {
                    resultDigest = digestCalculator.GetDigest();
                }
                else
                {
                    if (content != null)
                    {
                        content.Write(new CmsSignedGenerator.DigOutputStream(digest));
                    }
                    else if (signedAttributeSet == null)
                    {
                        // TODO Get rid of this exception and just treat content==null as empty not missing?
                        throw new CmsException("data not encapsulated in signature - use detached constructor.");
                    }

                    resultDigest = DigestUtilities.DoFinal(digest);
                }
            }
            catch (IOException e)
            {
                throw new CmsException("can't process mime object to create signature.", e);
            }

            // TODO Shouldn't be using attribute OID as contentType (should be null)
            bool isCounterSignature = contentType.Equals(CmsAttributes.CounterSignature);

            // RFC 3852 11.1 Check the content-type attribute is correct
            {
                Asn1Object validContentType = GetSingleValuedSignedAttribute(
                    CmsAttributes.ContentType, "content-type");
                if (validContentType == null)
                {
                    if (!isCounterSignature && signedAttributeSet != null)
                    {
                        throw new CmsException("The content-type attribute type MUST be present whenever signed attributes are present in signed-data");
                    }
                }
                else
                {
                    if (isCounterSignature)
                    {
                        throw new CmsException("[For counter signatures,] the signedAttributes field MUST NOT contain a content-type attribute");
                    }

                    if (!(validContentType is DerObjectIdentifier))
                    {
                        throw new CmsException("content-type attribute value not of ASN.1 type 'OBJECT IDENTIFIER'");
                    }

                    DerObjectIdentifier signedContentType = (DerObjectIdentifier)validContentType;

                    if (!signedContentType.Equals(contentType))
                    {
                        throw new CmsException("content-type attribute value does not match eContentType");
                    }
                }
            }

            // RFC 3852 11.2 Check the message-digest attribute is correct
            {
                Asn1Object validMessageDigest = GetSingleValuedSignedAttribute(
                    CmsAttributes.MessageDigest, "message-digest");
                if (validMessageDigest == null)
                {
                    if (signedAttributeSet != null)
                    {
                        throw new CmsException("the message-digest signed attribute type MUST be present when there are any signed attributes present");
                    }
                }
                else
                {
                    if (!(validMessageDigest is Asn1OctetString))
                    {
                        throw new CmsException("message-digest attribute value not of ASN.1 type 'OCTET STRING'");
                    }

                    Asn1OctetString signedMessageDigest = (Asn1OctetString)validMessageDigest;

                    if (!Arrays.AreEqual(resultDigest, signedMessageDigest.GetOctets()))
                    {
                        throw new CmsException("message-digest attribute value does not match calculated value");
                    }
                }
            }

            // RFC 3852 11.4 Validate countersignature attribute(s)
            {
                Asn1.Cms.AttributeTable signedAttrTable = this.SignedAttributes;
                if (signedAttrTable != null &&
                    signedAttrTable.GetAll(CmsAttributes.CounterSignature).Count > 0)
                {
                    throw new CmsException("A countersignature attribute MUST NOT be a signed attribute");
                }

                Asn1.Cms.AttributeTable unsignedAttrTable = this.UnsignedAttributes;
                if (unsignedAttrTable != null)
                {
                    foreach (Asn1.Cms.Attribute csAttr in unsignedAttrTable.GetAll(CmsAttributes.CounterSignature))
                    {
                        if (csAttr.AttrValues.Count < 1)
                        {
                            throw new CmsException("A countersignature attribute MUST contain at least one AttributeValue");
                        }

                        // Note: We don't recursively validate the countersignature value
                    }
                }
            }

            try
            {
                sig.Init(false, key);

                if (signedAttributeSet == null)
                {
                    if (digestCalculator != null)
                    {
                        // need to decrypt signature and check message bytes
                        return(VerifyDigest(resultDigest, key, this.GetSignature()));
                    }
                    else if (content != null)
                    {
                        // TODO Use raw signature of the hash value instead
                        content.Write(new CmsSignedGenerator.SigOutputStream(sig));
                    }
                }
                else
                {
                    byte[] tmp = this.GetEncodedSignedAttributes();
                    sig.BlockUpdate(tmp, 0, tmp.Length);
                }

                return(sig.VerifySignature(this.GetSignature()));
            }
            catch (InvalidKeyException e)
            {
                throw new CmsException("key not appropriate to signature in message.", e);
            }
            catch (IOException e)
            {
                throw new CmsException("can't process mime object to create signature.", e);
            }
            catch (SignatureException e)
            {
                throw new CmsException("invalid signature format in message: " + e.Message, e);
            }
        }
 public X509Crl Generate(AsymmetricKeyParameter privateKey, SecureRandom random)
 {
     return(Generate(new Asn1SignatureFactory(signatureAlgorithm, privateKey, random)));
 }
		public virtual ISigner CreateSigner(SecureRandom random, AsymmetricKeyParameter privateKey)
		{
			return MakeSigner(new Sha1Digest(), true, new ParametersWithRandom(privateKey, random));
		}
 public Asn1VerifierFactoryProvider(AsymmetricKeyParameter publicKey)
 {
     this.publicKey = publicKey;
 }
 public override ISigner CreateVerifyer(SignatureAndHashAlgorithm algorithm, AsymmetricKeyParameter publicKey)
 {
     return(MakeSigner(algorithm, false, false, publicKey));
 }
Exemple #52
0
        /*
         * creates a certificate and a private key and installs into windows registry
         */
        public static void CreateCertificateKey(
            string subjectName,
            string issuerName,
            string signatureAlgorithm,
            int strength,
            DateTime begin,
            DateTime end,
            string subjectCountryCode,
            string subjectOrganization,
            string subjectTitle,
            string issuerCountryCode,
            string issuerOrganization,
            string issuerTitle,
            string subjectCommonName,
            string issuerCommonName)
        {
            // creating key pair
            RsaKeyPairGenerator keyPairGenerator = new RsaKeyPairGenerator();
            SecureRandom        secureRandom     = new SecureRandom(new CryptoApiRandomGenerator());

            keyPairGenerator.Init(new KeyGenerationParameters(secureRandom, strength));
            AsymmetricCipherKeyPair    asCipherKeyPair = keyPairGenerator.GenerateKeyPair();
            AsymmetricKeyParameter     publicKey       = asCipherKeyPair.Public;
            RsaPrivateCrtKeyParameters privateKey      = (RsaPrivateCrtKeyParameters)asCipherKeyPair.Private;

            // initializing certificate generator
            X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();
            BigInteger serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), secureRandom);

            certificateGenerator.SetSerialNumber(serialNumber);

            // setting subject name
            string subjectNameString = "E=" + subjectName;

            if (subjectCommonName != null)
            {
                subjectNameString += ", CN=" + subjectCommonName;
            }
            if (subjectCountryCode != null)
            {
                subjectNameString += ", C=" + subjectCountryCode;
            }
            if (subjectOrganization != null)
            {
                subjectNameString += ", O=" + subjectOrganization;
            }
            if (subjectTitle != null)
            {
                subjectNameString += ", T=" + subjectTitle;
            }
            certificateGenerator.SetSubjectDN(new X509Name(subjectNameString));

            // setting issuer name
            string issuerNameString = "E=" + issuerName;

            if (issuerCommonName != null)
            {
                issuerNameString += ", CN=" + issuerCommonName;
            }
            if (issuerCountryCode != null)
            {
                issuerNameString += ", C=" + issuerCountryCode;
            }
            if (issuerOrganization != null)
            {
                issuerNameString += ", O=" + issuerOrganization;
            }
            if (issuerTitle != null)
            {
                issuerNameString += ", T=" + issuerTitle;
            }
            certificateGenerator.SetIssuerDN(new X509Name(issuerNameString));

            // setting other properties of certificate
            certificateGenerator.SetNotBefore(begin);
            certificateGenerator.SetNotAfter(end);
            certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm);
            certificateGenerator.SetPublicKey(publicKey);

            // setting key usage
            KeyPurposeID[] usages = new KeyPurposeID[] { KeyPurposeID.IdKPEmailProtection };
            certificateGenerator.AddExtension(
                X509Extensions.ExtendedKeyUsage.Id,
                false,
                new ExtendedKeyUsage(usages));

            // creating certificate and installing into certificate/key database
            X509Certificate certificate = certificateGenerator.Generate(privateKey);

            sys.X509Certificate2 windowsCertificate = new sys.X509Certificate2(DotNetUtilities.ToX509Certificate(certificate));
            windowsCertificate.PrivateKey = ConvertToSystemKey(privateKey);
            InstallIntoRegistry(windowsCertificate);
        }
 public override bool IsValidPublicKey(AsymmetricKeyParameter publicKey)
 {
     return(publicKey is RsaKeyParameters && !publicKey.IsPrivate);
 }
 public override bool IsValidPublicKey(AsymmetricKeyParameter publicKey)
 {
     return publicKey is DsaPublicKeyParameters;
 }
		public virtual ISigner CreateVerifyer(AsymmetricKeyParameter publicKey)
		{
			return MakeSigner(new Sha1Digest(), false, publicKey);
		}
    /// <summary>
    /// Revoke the CA signed certificate.
    /// The issuer CA public key, the private key and the crl reside in the storepath.
    /// The CRL number is increased by one and existing CRL for the issuer are deleted from the store.
    /// </summary>
    public static async Task <X509CRL> RevokeCertificateAsync(
        string storePath,
        X509Certificate2 certificate,
        string issuerKeyFilePassword = null
        )
    {
        X509CRL updatedCRL = null;

        try
        {
            string subjectName  = certificate.IssuerName.Name;
            string keyId        = null;
            string serialNumber = null;

            // caller may want to create empty CRL using the CA cert itself
            bool isCACert = IsCertificateAuthority(certificate);

            // find the authority key identifier.
            X509AuthorityKeyIdentifierExtension authority = FindAuthorityKeyIdentifier(certificate);

            if (authority != null)
            {
                keyId        = authority.KeyId;
                serialNumber = authority.SerialNumber;
            }
            else
            {
                throw new ArgumentException("Certificate does not contain an Authority Key");
            }

            if (!isCACert)
            {
                if (serialNumber == certificate.SerialNumber ||
                    Utils.CompareDistinguishedName(certificate.Subject, certificate.Issuer))
                {
                    throw new ServiceResultException(StatusCodes.BadCertificateInvalid, "Cannot revoke self signed certificates");
                }
            }

            X509Certificate2 certCA = null;
            using (ICertificateStore store = CertificateStoreIdentifier.OpenStore(storePath))
            {
                if (store == null)
                {
                    throw new ArgumentException("Invalid store path/type");
                }
                certCA = await FindIssuerCABySerialNumberAsync(store, certificate.Issuer, serialNumber);

                if (certCA == null)
                {
                    throw new ServiceResultException(StatusCodes.BadCertificateInvalid, "Cannot find issuer certificate in store.");
                }

                if (!certCA.HasPrivateKey)
                {
                    throw new ServiceResultException(StatusCodes.BadCertificateInvalid, "Issuer certificate has no private key, cannot revoke certificate.");
                }

                CertificateIdentifier certCAIdentifier = new CertificateIdentifier(certCA);
                certCAIdentifier.StorePath = storePath;
                certCAIdentifier.StoreType = CertificateStoreIdentifier.DetermineStoreType(storePath);
                X509Certificate2 certCAWithPrivateKey = await certCAIdentifier.LoadPrivateKey(issuerKeyFilePassword);

                if (certCAWithPrivateKey == null)
                {
                    throw new ServiceResultException(StatusCodes.BadCertificateInvalid, "Failed to load issuer private key. Is the password correct?");
                }

                List <X509CRL> certCACrl = store.EnumerateCRLs(certCA, false);

                using (var cfrg = new CertificateFactoryRandomGenerator())
                {
                    // cert generators
                    SecureRandom random          = new SecureRandom(cfrg);
                    BigInteger   crlSerialNumber = BigInteger.Zero;

                    Org.BouncyCastle.X509.X509Certificate bcCertCA = new X509CertificateParser().ReadCertificate(certCA.RawData);
                    AsymmetricKeyParameter signingKey = GetPrivateKeyParameter(certCAWithPrivateKey);

                    ISignatureFactory signatureFactory =
                        new Asn1SignatureFactory(GetRSAHashAlgorithm(defaultHashSize), signingKey, random);

                    X509V2CrlGenerator crlGen = new X509V2CrlGenerator();
                    crlGen.SetIssuerDN(bcCertCA.IssuerDN);
                    crlGen.SetThisUpdate(DateTime.UtcNow);
                    crlGen.SetNextUpdate(DateTime.UtcNow.AddMonths(12));

                    // merge all existing revocation list
                    X509CrlParser parser = new X509CrlParser();
                    foreach (X509CRL caCrl in certCACrl)
                    {
                        X509Crl crl = parser.ReadCrl(caCrl.RawData);
                        crlGen.AddCrl(crl);
                        var crlVersion = GetCrlNumber(crl);
                        if (crlVersion.IntValue > crlSerialNumber.IntValue)
                        {
                            crlSerialNumber = crlVersion;
                        }
                    }

                    if (isCACert)
                    {
                        // add a dummy revoked cert
                        crlGen.AddCrlEntry(BigInteger.One, DateTime.UtcNow, CrlReason.Superseded);
                    }
                    else
                    {
                        // add the revoked cert
                        crlGen.AddCrlEntry(GetSerialNumber(certificate), DateTime.UtcNow, CrlReason.PrivilegeWithdrawn);
                    }

                    crlGen.AddExtension(X509Extensions.AuthorityKeyIdentifier,
                                        false,
                                        new AuthorityKeyIdentifierStructure(bcCertCA));

                    // set new serial number
                    crlSerialNumber = crlSerialNumber.Add(BigInteger.One);
                    crlGen.AddExtension(X509Extensions.CrlNumber,
                                        false,
                                        new CrlNumber(crlSerialNumber));

                    // generate updated CRL
                    X509Crl updatedCrl = crlGen.Generate(signatureFactory);

                    // add updated CRL to store
                    updatedCRL = new X509CRL(updatedCrl.GetEncoded());
                    store.AddCRL(updatedCRL);

                    // delete outdated CRLs from store
                    foreach (X509CRL caCrl in certCACrl)
                    {
                        store.DeleteCRL(caCrl);
                    }
                }
                store.Close();
            }
        }
        catch (Exception e)
        {
            throw e;
        }
        return(updatedCRL);
    }
 public DefaultTlsSignerCredentials(TlsContext context, Certificate certificate, AsymmetricKeyParameter privateKey)
     : this(context, certificate, privateKey, null)
 {
 }
    /// <summary>
    /// Creates a certificate signing request from an existing certificate.
    /// </summary>
    public static byte[] CreateSigningRequest(
        X509Certificate2 certificate,
        IList <String> domainNames = null
        )
    {
        using (var cfrg = new CertificateFactoryRandomGenerator())
        {
            SecureRandom random = new SecureRandom(cfrg);

            // try to get signing/private key from certificate passed in
            AsymmetricKeyParameter signingKey = GetPrivateKeyParameter(certificate);
            RsaKeyParameters       publicKey  = GetPublicKeyParameter(certificate);

            ISignatureFactory signatureFactory =
                new Asn1SignatureFactory(GetRSAHashAlgorithm(defaultHashSize), signingKey, random);

            Asn1Set attributes = null;
            X509SubjectAltNameExtension alternateName = null;
            foreach (System.Security.Cryptography.X509Certificates.X509Extension extension in certificate.Extensions)
            {
                if (extension.Oid.Value == X509SubjectAltNameExtension.SubjectAltNameOid || extension.Oid.Value == X509SubjectAltNameExtension.SubjectAltName2Oid)
                {
                    alternateName = new X509SubjectAltNameExtension(extension, extension.Critical);
                    break;
                }
            }

            domainNames = domainNames ?? new List <String>();
            if (alternateName != null)
            {
                foreach (var name in alternateName.DomainNames)
                {
                    if (!domainNames.Any(s => s.Equals(name, StringComparison.OrdinalIgnoreCase)))
                    {
                        domainNames.Add(name);
                    }
                }
                foreach (var ipAddress in alternateName.IPAddresses)
                {
                    if (!domainNames.Any(s => s.Equals(ipAddress, StringComparison.OrdinalIgnoreCase)))
                    {
                        domainNames.Add(ipAddress);
                    }
                }
            }

            if (domainNames.Count > 0)
            {
                List <GeneralName> generalNames = CreateSubjectAlternateNameDomains(domainNames);
                if (generalNames.Count > 0)
                {
                    IList oids   = new ArrayList();
                    IList values = new ArrayList();
                    oids.Add(X509Extensions.SubjectAlternativeName);
                    values.Add(new Org.BouncyCastle.Asn1.X509.X509Extension(false,
                                                                            new DerOctetString(new GeneralNames(generalNames.ToArray()).GetDerEncoded())));

                    AttributePkcs attribute = new AttributePkcs(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest,
                                                                new DerSet(new X509Extensions(oids, values)));

                    attributes = new DerSet(attribute);
                }
            }

            Pkcs10CertificationRequest pkcs10CertificationRequest = new Pkcs10CertificationRequest(
                signatureFactory,
                new CertificateFactoryX509Name(false, certificate.Subject),
                publicKey,
                attributes,
                signingKey);

            return(pkcs10CertificationRequest.GetEncoded());
        }
    }
 /// <exception cref="IOException"></exception>
 public abstract byte[] GenerateAgreement(AsymmetricKeyParameter peerPublicKey);
 public DefaultTlsSignerCredentials(TlsContext context, Certificate certificate, AsymmetricKeyParameter privateKey, SignatureAndHashAlgorithm signatureAndHashAlgorithm)
 {
     //IL_000e: Unknown result type (might be due to invalid IL or missing references)
     //IL_0026: Unknown result type (might be due to invalid IL or missing references)
     //IL_0034: Unknown result type (might be due to invalid IL or missing references)
     //IL_004c: Unknown result type (might be due to invalid IL or missing references)
     //IL_0068: Unknown result type (might be due to invalid IL or missing references)
     //IL_00c2: Unknown result type (might be due to invalid IL or missing references)
     if (certificate == null)
     {
         throw new ArgumentNullException("certificate");
     }
     if (certificate.IsEmpty)
     {
         throw new ArgumentException("cannot be empty", "clientCertificate");
     }
     if (privateKey == null)
     {
         throw new ArgumentNullException("privateKey");
     }
     if (!privateKey.IsPrivate)
     {
         throw new ArgumentException("must be private", "privateKey");
     }
     if (TlsUtilities.IsTlsV12(context) && signatureAndHashAlgorithm == null)
     {
         throw new ArgumentException("cannot be null for (D)TLS 1.2+", "signatureAndHashAlgorithm");
     }
     if (privateKey is RsaKeyParameters)
     {
         mSigner = new TlsRsaSigner();
     }
     else if (privateKey is DsaPrivateKeyParameters)
     {
         mSigner = new TlsDssSigner();
     }
     else
     {
         if (!(privateKey is ECPrivateKeyParameters))
         {
             throw new ArgumentException("type not supported: " + Platform.GetTypeName(privateKey), "privateKey");
         }
         mSigner = new TlsECDsaSigner();
     }
     mSigner.Init(context);
     mContext     = context;
     mCertificate = certificate;
     mPrivateKey  = privateKey;
     mSignatureAndHashAlgorithm = signatureAndHashAlgorithm;
 }