Inheritance: IAsymmetricKeyParameter
 /**
 * add a signer - no attributes other than the default ones will be
 * provided here.
 *
 * @param key signing key to use
 * @param cert certificate containing corresponding public key
 * @param digestOID digest algorithm OID
 */
 public void AddSigner(
     AsymmetricKeyParameter	privateKey,
     X509Certificate			cert,
     string					digestOID)
 {
     AddSigner(privateKey, cert, GetEncOid(privateKey, digestOID), digestOID);
 }
        public virtual void ProcessServerCertificate(Certificate serverCertificate)
        {
            if (tlsSigner == null)
            {
                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);
            }

            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."
            */
        }
        /// <summary>
        /// Generate a new X509Certificate specifying a SecureRandom instance that you would like to use.
        /// </summary>
        /// <param name="privateKey">The private key of the issuer used to sign this certificate.</param>
        /// <param name="random">The Secure Random you want to use.</param>
        /// <returns>An X509Certificate.</returns>
        public X509Certificate Generate(
            AsymmetricKeyParameter	privateKey,
            SecureRandom			random)
        {
            TbsCertificateStructure tbsCert = tbsGen.GenerateTbsCertificate();
            byte[] signature;

            try
            {
                signature = X509Utilities.GetSignatureForObject(
                    sigOID, signatureAlgorithm, privateKey, random, tbsCert);
            }
            catch (Exception e)
            {
                // TODO
            //				throw new ExtCertificateEncodingException("exception encoding TBS cert", e);
                throw new CertificateEncodingException("exception encoding TBS cert", e);
            }

            try
            {
                return GenerateJcaObject(tbsCert, signature);
            }
            catch (CertificateParsingException e)
            {
                // TODO
                // throw new ExtCertificateEncodingException("exception producing certificate object", e);
                throw new CertificateEncodingException("exception producing certificate object", e);
            }
        }
Exemplo n.º 4
0
        private X509Certificate Create(CertificateRequest request, AsymmetricKeyParameter key)
        {
            try
            {
                var certGen = new X509V3CertificateGenerator();

                certGen.SetSerialNumber(BigInteger.ProbablePrime(128, new SecureRandom()));

                certGen.SetIssuerDN(new X509Name(_issuer));

                certGen.SetNotBefore(request.NotBefore);
                certGen.SetNotAfter(request.NotAfter);

                certGen.SetSubjectDN(new X509Name(_subject));
                certGen.SetPublicKey(_subjectPublicKey.PublicAsymmetricKey);

                certGen.SetSignatureAlgorithm("SHA1WITHRSA");

                certGen.AddExtension(X509Extensions.BasicConstraints, false, new BasicConstraints(true));

                return certGen.Generate(key);
            }
            catch (Exception e)
            {
                throw new SecularException("Error generating certificate: " + e.Message, e);
            }
        }
Exemplo n.º 5
0
		public byte[] CalculateRawSignature(AsymmetricKeyParameter privateKey, byte[] md5andsha1)
		{
			ISigner sig = new GenericSigner(new Pkcs1Encoding(new RsaBlindedEngine()), new NullDigest());
			sig.Init(true, privateKey);
			sig.BlockUpdate(md5andsha1, 0, md5andsha1.Length);
			return sig.GenerateSignature();
		}
Exemplo n.º 6
0
        public virtual void ProcessServerCertificate(Certificate serverCertificate)
        {
            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."
            */
        }
        private AsymmetricKeyParameter GetSenderPublicKey(
            AsymmetricKeyParameter		receiverPrivateKey,
            OriginatorIdentifierOrKey	originator)
        {
            OriginatorPublicKey opk = originator.OriginatorPublicKey;
            if (opk != null)
            {
                return GetPublicKeyFromOriginatorPublicKey(receiverPrivateKey, opk);
            }
            
            OriginatorID origID = new OriginatorID();
            
            Asn1.Cms.IssuerAndSerialNumber iAndSN = originator.IssuerAndSerialNumber;
            if (iAndSN != null)
            {
                origID.Issuer = iAndSN.Name;
                origID.SerialNumber = iAndSN.SerialNumber.Value;
            }
            else
            {
                SubjectKeyIdentifier ski = originator.SubjectKeyIdentifier;

                origID.SubjectKeyIdentifier = ski.GetKeyIdentifier();
            }

            return GetPublicKeyFromOriginatorID(origID);
        }
			internal SignerInfoGeneratorImpl(
				CmsSignedDataStreamGenerator	outer,
				AsymmetricKeyParameter			key,
				SignerIdentifier				signerIdentifier,
				string							digestOID,
				string							encOID,
				CmsAttributeTableGenerator		sAttr,
				CmsAttributeTableGenerator		unsAttr)
			{
				this.outer = outer;

				_signerIdentifier = signerIdentifier;
				_digestOID = digestOID;
				_encOID = encOID;
				_sAttr = sAttr;
				_unsAttr = unsAttr;
				_encName = Helper.GetEncryptionAlgName(_encOID);

				string digestName = Helper.GetDigestAlgName(_digestOID);
				string signatureName = digestName + "with" + _encName;

				if (_sAttr != null)
				{
            		_sig = Helper.GetSignatureInstance(signatureName);
				}
				else
				{
					// Note: Need to use raw signatures here since we have already calculated the digest
					if (_encName.Equals("RSA"))
					{
						_sig = Helper.GetSignatureInstance("RSA");
					}
					else if (_encName.Equals("DSA"))
					{
						_sig = Helper.GetSignatureInstance("NONEwithDSA");
					}
					// TODO Add support for raw PSS
//					else if (_encName.equals("RSAandMGF1"))
//					{
//						_sig = CMSSignedHelper.INSTANCE.getSignatureInstance("NONEWITHRSAPSS", _sigProvider);
//						try
//						{
//							// Init the params this way to avoid having a 'raw' version of each PSS algorithm
//							Signature sig2 = CMSSignedHelper.INSTANCE.getSignatureInstance(signatureName, _sigProvider);
//							PSSParameterSpec spec = (PSSParameterSpec)sig2.getParameters().getParameterSpec(PSSParameterSpec.class);
//							_sig.setParameter(spec);
//						}
//						catch (Exception e)
//						{
//							throw new SignatureException("algorithm: " + _encName + " could not be configured.");
//						}
//					}
					else
					{
						throw new SignatureException("algorithm: " + _encName + " not supported in base signatures.");
					}
				}

				_sig.Init(true, new ParametersWithRandom(key, outer.rand));
			}
Exemplo n.º 9
0
        //Generates and returns a new transaction from this wallet.
        public Transaction sendFunds(Org.BouncyCastle.Crypto.AsymmetricKeyParameter _recipient, float value)
        {
            if (getBalance() < value)
            { //gather balance and check funds.
                Console.WriteLine("#Not Enough funds to send transaction. Transaction Discarded.");
                return(null);
            }
            //create array list of inputs
            List <TransactionInput> inputs = new List <TransactionInput>();

            float total = 0;

            foreach (KeyValuePair <string, TransactionOutput> item in UTXOs)
            {
                TransactionOutput UTXO = item.Value;
                total += UTXO.value;
                inputs.Add(new TransactionInput(UTXO.id));
                if (total > value)
                {
                    break;
                }
            }

            Transaction newTransaction = new Transaction(publicKey, _recipient, value, inputs);

            newTransaction.generateSignature(privateKey);

            foreach (TransactionInput input in inputs)
            {
                UTXOs.Remove(input.transactionOutputId);
            }
            return(newTransaction);
        }
Exemplo n.º 10
0
 public AsymmetricKeyEntry(
     AsymmetricKeyParameter	key,
     Hashtable				attributes)
     : base(attributes)
 {
     this.key = key;
 }
Exemplo n.º 11
0
		/// <summary>
		/// Initializes a new instance of the <see cref="MimeKit.Cryptography.CmsSigner"/> class.
		/// </summary>
		/// <remarks>
		/// <para>The initial value of the <see cref="DigestAlgorithm"/> will be set to
		/// <see cref="MimeKit.Cryptography.DigestAlgorithm.Sha1"/> and both the
		/// <see cref="SignedAttributes"/> and <see cref="UnsignedAttributes"/> properties
		/// will be initialized to empty tables.</para>
		/// </remarks>
		/// <param name="chain">The chain of certificates starting with the signer's certificate back to the root.</param>
		/// <param name="key">The signer's private key.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <para><paramref name="chain"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="key"/> is <c>null</c>.</para>
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// <para><paramref name="chain"/> did not contain any certificates.</para>
		/// <para>-or-</para>
		/// <para>The certificate cannot be used for signing.</para>
		/// <para>-or-</para>
		/// <para><paramref name="key"/> is not a private key.</para>
		/// </exception>
		public CmsSigner (IEnumerable<X509CertificateEntry> chain, AsymmetricKeyParameter key) : this ()
		{
			if (chain == null)
				throw new ArgumentNullException ("chain");

			if (key == null)
				throw new ArgumentNullException ("key");

			CertificateChain = new X509CertificateChain ();
			foreach (var entry in chain) {
				CertificateChain.Add (entry.Certificate);
				if (Certificate == null)
					Certificate = entry.Certificate;
			}

			if (CertificateChain.Count == 0)
				throw new ArgumentException ("The certificate chain was empty.", "chain");

			var flags = Certificate.GetKeyUsageFlags ();
			if (flags != X509KeyUsageFlags.None && (flags & X509KeyUsageFlags.DigitalSignature) == 0)
				throw new ArgumentException ("The certificate cannot be used for signing.");

			if (!key.IsPrivate)
				throw new ArgumentException ("The key must be a private key.", "key");

			PrivateKey = key;
		}
Exemplo n.º 12
0
		/**
		* Constructor for an encrypted private key PEM object.
		*
		* @param key       private key to be encoded
		* @param algorithm encryption algorithm to use
		* @param provider  provider to use
		* @throws NoSuchAlgorithmException if algorithm/mode cannot be found
		*/
		public Pkcs8Generator(AsymmetricKeyParameter privKey, string algorithm)
		{
			// TODO Check privKey.IsPrivate
			this.privKey = privKey;
			this.algorithm = algorithm;
			this.iterationCount = 2048;
		}
Exemplo n.º 13
0
        public AsymmetricKeyEntry(
            AsymmetricKeyParameter  key,
            IDictionary             attributes)
			: base(attributes)
        {
            this.key = key;
        }
Exemplo n.º 14
0
        private static int sequence = 0; // a rough count of how many transactions have been generated.

        // Constructor:
        public Transaction(Org.BouncyCastle.Crypto.AsymmetricKeyParameter from, Org.BouncyCastle.Crypto.AsymmetricKeyParameter to, float value, List <TransactionInput> inputs)
        {
            this.sender     = from;
            this.reciepient = to;
            this.value      = value;
            this.inputs     = inputs;
        }
Exemplo n.º 15
0
	    private Connection GetConnectionHttpsPrivate(Uri uri, Uri proxy, AsymmetricKeyParameter asymmetricKeyParameter,
	                                                 Certificate clientCertificates,
	                                                 Action<Certificate> serverCertificateValidator)
	    {
			Connection conn = new HttpsConnection(this, uri, proxy, clientCertificates, asymmetricKeyParameter, serverCertificateValidator);
		    return InitiateConnection(conn);
	    }
Exemplo n.º 16
0
        public static Org.BouncyCastle.X509.X509Certificate CreateCert(String cn,
            AsymmetricKeyParameter pubKey, AsymmetricKeyParameter privKey)
        {
            Hashtable attrs = new Hashtable();
            attrs.Add(X509Name.CN, cn);

            ArrayList ord = new ArrayList(attrs.Keys);

            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

            certGen.SetSerialNumber(BigInteger.One);
            certGen.SetIssuerDN(new X509Name(ord, attrs));
            certGen.SetNotBefore(DateTime.UtcNow.AddDays(-30));
            certGen.SetNotAfter(DateTime.UtcNow.AddDays(30));
            certGen.SetSubjectDN(new X509Name(ord, attrs));
            certGen.SetPublicKey(pubKey);
            certGen.SetSignatureAlgorithm("SHA1WithRSAEncryption");

            Org.BouncyCastle.X509.X509Certificate cert = certGen.Generate(privKey);

            cert.CheckValidity(DateTime.UtcNow);

            cert.Verify(pubKey);

            return cert;
        }
Exemplo n.º 17
0
		public void ProcessServerCertificate(Certificate serverCertificate)
		{
			if (tlsSigner == null)
			{
				handler.FailWithError(TlsProtocolHandler.AL_fatal, TlsProtocolHandler.AP_unexpected_message);
			}

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

			try
			{
				this.serverPublicKey = PublicKeyFactory.CreateKey(keyInfo);
			}
//			catch (RuntimeException)
			catch (Exception)
			{
				handler.FailWithError(TlsProtocolHandler.AL_fatal, TlsProtocolHandler.AP_unsupported_certificate);
			}

			// Sanity check the PublicKeyFactory
			if (this.serverPublicKey.IsPrivate)
			{
				handler.FailWithError(TlsProtocolHandler.AL_fatal, TlsProtocolHandler.AP_internal_error);
			}

			// 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."
			*/
			switch (this.keyExchange)
			{
				case TlsKeyExchangeAlgorithm.KE_SRP_RSA:
				if (!(this.serverPublicKey is RsaKeyParameters))
				{
					handler.FailWithError(TlsProtocolHandler.AL_fatal, TlsProtocolHandler.AP_certificate_unknown);
				}
				ValidateKeyUsage(x509Cert, KeyUsage.DigitalSignature);
				break;
			case TlsKeyExchangeAlgorithm.KE_SRP_DSS:
				if (!(this.serverPublicKey is DsaPublicKeyParameters))
				{
					handler.FailWithError(TlsProtocolHandler.AL_fatal, TlsProtocolHandler.AP_certificate_unknown);
				}
				break;
			default:
				handler.FailWithError(TlsProtocolHandler.AL_fatal, TlsProtocolHandler.AP_unsupported_certificate);
				break;
			}

			/*
			* Verify them.
			*/
			if (!this.verifyer.IsValid(serverCertificate.GetCerts()))
			{
				handler.FailWithError(TlsProtocolHandler.AL_fatal, TlsProtocolHandler.AP_user_canceled);
			}
		}
 /// <summary>
 /// Retorna el sello digital para el certificado y firmando con la llave.
 /// </summary>
 /// <param name="rutaLlave"></param>
 /// <param name="clavePrivada"></param>
 /// <param name="cadenaOriginal"></param>
 /// <returns></returns>
 public string GetSelloDigital(ref string error, string rutaLlave, string clavePrivada, string cadenaOriginal)
 {
     try
     {
         byte[] ArrayKey = File.ReadAllBytes(rutaLlave); // Convertimos el archivo anterior a byte
         //1) Desencriptar la llave privada, el primer parámetro es la contraseña de llave privada y el segundo es la llave privada en formato binario.
         Org.BouncyCastle.Crypto.AsymmetricKeyParameter asp = Org.BouncyCastle.Security.PrivateKeyFactory.DecryptKey(clavePrivada.ToCharArray(), ArrayKey);
         //2) Convertir a parámetros de RSA
         Org.BouncyCastle.Crypto.Parameters.RsaKeyParameters key = (Org.BouncyCastle.Crypto.Parameters.RsaKeyParameters)asp;
         //3) Crear el firmador con SHA1
         Org.BouncyCastle.Crypto.ISigner sig = Org.BouncyCastle.Security.SignerUtilities.GetSigner("SHA-256withRSA");
         //La siguiente linea es para generar el sello para la nueva versión de CFDI 3.3
         // Org.BouncyCastle.Crypto.ISigner sig = Org.BouncyCastle.Security.SignerUtilities.GetSigner("SHA-256withRSA");
         //4) Inicializar el firmador con la llave privada
         sig.Init(true, key);
         // 5) Pasar la cadena original a formato binario
         byte[] bytes = Encoding.UTF8.GetBytes(cadenaOriginal);
         // 6) Encriptar
         sig.BlockUpdate(bytes, 0, bytes.Length);
         byte[] bytesFirmados = sig.GenerateSignature();
         // 7) Finalmente obtenemos el sello
         String sello = Convert.ToBase64String(bytesFirmados);
         return(sello);
     }
     catch (Exception e)
     {
         _logger.EscribirError(e.ToString());
         error = "Problemas al generar xml para el timbrado, favor revisar clave o certificados.";
         return("");
     }
 }
Exemplo n.º 19
0
 public static BigInteger ComputeSharedSecret(string A, AsymmetricKeyParameter bPrivateKey, DHParameters internalParameters)
 {
     var importedKey = new DHPublicKeyParameters(new BigInteger(A), internalParameters);
     var internalKeyAgree = AgreementUtilities.GetBasicAgreement("DH");
     internalKeyAgree.Init(bPrivateKey);
     return internalKeyAgree.CalculateAgreement(importedKey);
 }
Exemplo n.º 20
0
        public static void CreateSignature(System.Security.Cryptography.X509Certificates.X509Certificate2 mycert)
        {
            // https://www.programcreek.com/java-api-examples/?api=org.bouncycastle.x509.X509V3CertificateGenerator
            // https://forums.asp.net/t/2154987.aspx?Create+Self+Signed+Certificate+programatically+uisng+C+

            // System.Security.Cryptography.X509Certificates.X509Certificate2.CreateFromCertFile()


            // https://overcoder.net/q/429916/bouncycastle-privatekey-to-x509%D1%81%D0%B5%D1%80%D1%82%D0%B8%D1%84%D0%B8%D0%BA%D0%B0%D1%822-privatekey
            // https://www.csharpcodi.com/csharp-examples/Org.BouncyCastle.X509.X509Certificate.GetPublicKey()/

            AsymmetricKeyParameter Akp = Org.BouncyCastle.Security.DotNetUtilities.GetKeyPair(mycert.PrivateKey).Private;


            // if(mycert.HasPrivateKey)
            AsymmetricKeyParameter bouncyCastlePrivateKey = TransformRSAPrivateKey(mycert.PrivateKey);



            X509CertificateParser certParser        = new X509CertificateParser();
            X509Certificate       bouncyCertificate = certParser.ReadCertificate(mycert.GetRawCertData());

            Org.BouncyCastle.Crypto.AsymmetricKeyParameter pubKey = bouncyCertificate.GetPublicKey();

            var algorithm = Org.BouncyCastle.Security.DigestUtilities.GetDigest(bouncyCertificate.SigAlgOid);
            // var signature = new X509Certificate2Signature(mycert, algorithm);
            // https://github.com/kusl/itextsharp/blob/master/tags/iTextSharp_5_4_5/src/core/iTextSharp/text/pdf/security/X509Certificate2Signature.cs
            // Sign

            // PemReader pem = new PemReader();
            // pem.ReadPemObject().Headers
            // RSACryptoServiceProvider rsa = pem.ReadPrivateKeyFromFile("PrivateKey.pem");
        }
Exemplo n.º 21
0
        /**
         * create with a signer with extra signed/unsigned attributes.
         */
        public TimeStampTokenGenerator(
			AsymmetricKeyParameter	key,
			X509Certificate			cert,
			string					digestOID,
			string					tsaPolicyOID,
			Asn1.Cms.AttributeTable	signedAttr,
			Asn1.Cms.AttributeTable	unsignedAttr)
        {
            this.key = key;
            this.cert = cert;
            this.digestOID = digestOID;
            this.tsaPolicyOID = tsaPolicyOID;
            this.unsignedAttr = unsignedAttr;

            TspUtil.ValidateCertificate(cert);

            //
            // add the essCertid
            //
            Hashtable signedAttrs;
            if (signedAttr != null)
            {
                signedAttrs = signedAttr.ToHashtable();
            }
            else
            {
                signedAttrs = new Hashtable();
            }

            IDigest digest;
            try
            {
                digest = DigestUtilities.GetDigest("SHA-1");
            }
            catch (Exception e)
            {
                throw new TspException("Can't find a SHA-1 implementation.", e);
            }

            try
            {
                byte[] certEncoded = cert.GetEncoded();
                digest.BlockUpdate(certEncoded, 0, certEncoded.Length);
                byte[] hash = DigestUtilities.DoFinal(digest);

                EssCertID essCertid = new EssCertID(hash);

                Asn1.Cms.Attribute attr = new Asn1.Cms.Attribute(
                    PkcsObjectIdentifiers.IdAASigningCertificate,
                    new DerSet(new SigningCertificate(essCertid)));

                signedAttrs[attr.AttrType] = attr;
            }
            catch (CertificateEncodingException e)
            {
                throw new TspException("Exception processing certificate.", e);
            }

            this.signedAttr = new Asn1.Cms.AttributeTable(signedAttrs);
        }
		/**
		 * basic creation - only the default attributes will be included here.
		 */
		public TimeStampTokenGenerator(
			AsymmetricKeyParameter	key,
			X509Certificate			cert,
			string					digestOID,
			string					tsaPolicyOID)
			: this(key, cert, digestOID, tsaPolicyOID, null, null)
		{
		}
Exemplo n.º 23
0
 /// <summary>
 /// Encodes the public key into DER encoding.
 /// </summary>
 /// <param name="key">The public key.</param>
 /// <returns>The encoded public key.</returns>
 public static string ToPublicKeyString(AsymmetricKeyParameter key)
 {
     return
         Convert.ToBase64String(
             SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(key)
                                        .ToAsn1Object()
                                        .GetDerEncoded());
 }
Exemplo n.º 24
0
 /// <summary>
 /// Generates a user certificate
 /// </summary>
 /// <param name="subject">X509Name subject name </param>
 /// <param name="issuer">X509Name issuer name</param>
 /// <param name="iValidity">validity in days</param>
 /// <param name="publicKey">publickey</param>
 /// <param name="privateKey">private key of the issuer</param>
 /// <param name="signatureType">signature type</param>
 /// <param name="keyusages">keyusages, <see>Org.BouncyCastle.Asn1.X509.KeyUsage</see></param>
 /// <param name="extendedKeyUsages">extendedKeyUsages <see>Org.BouncyCastle.Asn1.X509.KeyPurposeID</see></param>
 /// <returns>brand new generated X509Certificate</returns>
 public static X509Certificate GenerateUserCertificate(X509Name subject, X509Name issuer,
                                                       int iValidity, AsymmetricKeyParameter publicKey,
                                                       AsymmetricKeyParameter privateKey, String signatureType,
                                                       int keyusages, ExtendedKeyUsage extendedKeyUsages)
 {
     return GenerateCertificate(subject, issuer, iValidity, publicKey, privateKey, signatureType, keyusages,
                                extendedKeyUsages, false, 0);
 }
Exemplo n.º 25
0
 public void Sign(AsymmetricKeyParameter privateKey)
 {
     var signer = new ECDsaSigner();
     signer.Init(true, privateKey);
     var signature = signer.GenerateSignature(t.getBytes);
     r = signature[0].ToByteArray();
     s = signature[1].ToByteArray();
 }
Exemplo n.º 26
0
        public static byte[] EncodeKeyParameter(AsymmetricKeyParameter key)
        {
            SubjectPublicKeyInfo publicKeyInfo
                = SubjectPublicKeyInfoFactory
                    .CreateSubjectPublicKeyInfo(key);

            return publicKeyInfo.ToAsn1Object().GetDerEncoded();
        }
 /**
 * add a signer - no attributes other than the default ones will be
 * provided here.
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 */
 public void AddSigner(
     AsymmetricKeyParameter	privateKey,
     X509Certificate			cert,
     string					digestOID)
 {
     AddSigner(privateKey, cert, digestOID,
         new DefaultSignedAttributeTableGenerator(), null);
 }
Exemplo n.º 28
0
 public string RsaEncrypt(string clearText, AsymmetricKeyParameter prywatny)
 {
     AsymmetricKeyParameter key = prywatny;
     var bytesToEncrypt = Encoding.UTF8.GetBytes(clearText);
     var encryptEngine = new Pkcs1Encoding(new RsaEngine());
     encryptEngine.Init(true, key);
     var encrypted = Convert.ToBase64String(encryptEngine.ProcessBlock(bytesToEncrypt, 0, bytesToEncrypt.Length));
     return encrypted;
 }
		public Pkcs10CertificationRequestDelaySigned(
			string					signatureAlgorithm,
			X509Name				subject,
			AsymmetricKeyParameter	publicKey,
			Asn1Set					attributes,
			AsymmetricKeyParameter	signingKey)
			: base(signatureAlgorithm, subject, publicKey, attributes, signingKey)
		{
		}
Exemplo n.º 30
0
 /// <summary>
 /// Generates a CA certificate.
 /// </summary>
 /// <param name="subject">X509Name subject name </param>
 /// <param name="iValidity">validity in days</param>
 /// <param name="publicKey">publickey</param>
 /// <param name="privateKey">private key of the issuer</param>
 /// <param name="signatureType">signature type</param>
 /// <param name="keyusages">keyusages, <see>Org.BouncyCastle.Asn1.X509.KeyUsage</see></param>
 /// <param name="extendedKeyUsages">extendedKeyUsages <see>Org.BouncyCastle.Asn1.X509.KeyPurposeID</see></param>
 /// <param name="pathLenConstraint"> </param>
 /// <returns>brand new generated X509Certificate</returns>
 public static X509Certificate GenerateCACertificate(X509Name subject,
                                                     int iValidity, AsymmetricKeyParameter publicKey,
                                                     AsymmetricKeyParameter privateKey, String signatureType,
                                                     int keyusages, ExtendedKeyUsage extendedKeyUsages,
                                                     int pathLenConstraint)
 {
     return GenerateCertificate(subject, subject, iValidity, publicKey, privateKey, signatureType, keyusages,
                                extendedKeyUsages, true, pathLenConstraint);
 }
 private static string GimmeKey(AsymmetricKeyParameter key)
 {
     var sb = new StringBuilder();
     using (var prvSw = new StringWriter(sb)) {
         var pmw = new Org.BouncyCastle.OpenSsl.PemWriter(prvSw);
         pmw.WriteObject(key);
     }
     return sb.ToString();
 }
Exemplo n.º 32
0
		internal CustomTlsClient(
			Certificate clientCertificates,
			AsymmetricKeyParameter asymmetricKeyParameter,
			Action<Certificate> serverCertificateValidator)
		{
			_clientCertificates = clientCertificates;
			_asymmetricKeyParameter = asymmetricKeyParameter;
			_serverCertificateValidator = serverCertificateValidator;
		}
Exemplo n.º 33
0
		public PgpKeyPair(
            PublicKeyAlgorithmTag	algorithm,
            AsymmetricKeyParameter	pubKey,
            AsymmetricKeyParameter	privKey,
            DateTime				time)
        {
            this.pub = new PgpPublicKey(algorithm, pubKey, time);
			this.priv = new PgpPrivateKey(privKey, pub.KeyId);
        }
Exemplo n.º 34
0
 public string RsaDecrypt(string base64Input, AsymmetricKeyParameter publiczny)
 {
     AsymmetricKeyParameter key = publiczny;
     var bytesToDecrypt = Convert.FromBase64String(base64Input);
     var decryptEngine = new Pkcs1Encoding(new RsaEngine());
     decryptEngine.Init(false, key);
     string decrypted = Encoding.UTF8.GetString(decryptEngine.ProcessBlock(bytesToDecrypt, 0, bytesToDecrypt.Length));
     return decrypted;
 }
Exemplo n.º 35
0
        public static TlsSignerCredentials LoadSignerCredentials(TlsContext context,
                                                                 string[] certResources, string keyResource,
                                                                 SignatureAndHashAlgorithm signatureAndHashAlgorithm)
        {
            Certificate certificate = LoadCertificateChain(certResources);

            Org.BouncyCastle.Crypto.AsymmetricKeyParameter privateKey = LoadPrivateKeyResource(keyResource);
            return(LoadSignerCredentials(context, certificate,
                                         privateKey, signatureAndHashAlgorithm));
        }
Exemplo n.º 36
0
        //Verifies a String signature
        public static bool verifyECDSASig(Org.BouncyCastle.Crypto.AsymmetricKeyParameter publicKey, string data, byte[] signature)
        {
            try
            {
                byte[] msgBytes = Encoding.UTF8.GetBytes(data);
                byte[] sigBytes = signature;

                ISigner signer = SignerUtilities.GetSigner("SHA-256withECDSA");
                signer.Init(false, publicKey);
                signer.BlockUpdate(msgBytes, 0, msgBytes.Length);
                return(signer.VerifySignature(sigBytes));
            }
            catch (Exception e)
            {
                throw new Exception("", e);
            }
        }
Exemplo n.º 37
0
 public void generateKeyPair()
 {
     try
     {
         ECKeyPairGenerator gen                      = new ECKeyPairGenerator("ECDSA");
         SecureRandom       secureRandom             = new SecureRandom();
         Org.BouncyCastle.Asn1.X9.X9ECParameters ecp = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp224k1");
         ECDomainParameters        ecSpec            = new ECDomainParameters(ecp.Curve, ecp.G, ecp.N, ecp.H, ecp.GetSeed());
         ECKeyGenerationParameters ecgp              = new ECKeyGenerationParameters(ecSpec, secureRandom);
         gen.Init(ecgp);
         AsymmetricCipherKeyPair eckp = gen.GenerateKeyPair();
         this.privateKey = eckp.Private;
         this.publicKey  = eckp.Public;
     }
     catch (Exception e)
     {
         throw new Exception("", e);
     }
 }
Exemplo n.º 38
0
        //Applies ECDSA Signature and returns the result ( as bytes ).
        public static byte[] applyECDSASig(Org.BouncyCastle.Crypto.AsymmetricKeyParameter privateKey, string input)
        {
            byte[] output = new byte[0];
            try
            {
                byte[] msgBytes = Encoding.UTF8.GetBytes(input);

                ISigner signer = SignerUtilities.GetSigner("SHA-256withECDSA");
                signer.Init(true, privateKey);
                signer.BlockUpdate(msgBytes, 0, msgBytes.Length);
                byte[] sigBytes = signer.GenerateSignature();

                output = sigBytes;
            }
            catch (Exception e)
            {
                throw new Exception("", e);
            }
            return(output);
        }
Exemplo n.º 39
0
        public void LoadCertificateFromPem(Stream stream)
        {
            List <byte[]> chain  = new List <byte[]>();
            PemReader     reader = new PemReader(new StreamReader(stream));
            PemObject     pem    = reader.ReadPemObject();

            while (pem != null)
            {
                if (pem.Type.EndsWith("CERTIFICATE"))
                {
                    chain.Add(pem.Content);
                }
                else if (pem.Type.EndsWith("PRIVATE KEY"))
                {
                    _PrivateKey = Certificates.GetPrivateKeyFromPEM(pem);
                }
                pem = reader.ReadPemObject();
            }
            _Certificate                 = new Certificate();
            _Certificate.CertChain       = chain;
            _Certificate.CertificateType = TCertificateType.X509;
        }
Exemplo n.º 40
0
        public void ExportRSAPublicKey(AsnFormat format)
        {
            using RSA rsa = RSA.Create(2048);
            byte[] exported = rsa.ExportRSAPublicKey(format);

            if (format == AsnFormat.Der)
            {
                SubjectPublicKeyInfo pski = new SubjectPublicKeyInfo(new AlgorithmIdentifier("1.2.840.113549.1.1.1"), exported);
                Org.BouncyCastle.Crypto.AsymmetricKeyParameter info = PublicKeyFactory.CreateKey(pski);
                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);
        }
Exemplo n.º 41
0
 public static string getStringFromKey(Org.BouncyCastle.Crypto.AsymmetricKeyParameter key)
 {
     return(System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(Convert.ToString(key.GetHashCode()))));
 }
Exemplo n.º 42
0
        //Signs all the data we dont wish to be tampered with.
        public void generateSignature(Org.BouncyCastle.Crypto.AsymmetricKeyParameter privateKey)
        {
            String data = StringUtil.getStringFromKey(sender) + StringUtil.getStringFromKey(reciepient) + Convert.ToString(value);

            signature = StringUtil.applyECDSASig(privateKey, data);
        }