/// <summary>
        /// Generate a public private key pair RSA crypto service provider.
        /// </summary>
        /// <param name="publicExponent">The public exponent (e; the public key is now represented as {e, n}).</param>
        /// <param name="strength">The strength of the cipher.</param>
        /// <returns>The RSA cryto service provider.</returns>
        public RSACryptoServiceProvider Generate(long publicExponent = 3, int strength = 4096)
        {
            // Create the rsa key paramaters from the strength and public exponent.
            Key.Crypto.Generators.RsaKeyPairGenerator        keyPair      = new Key.Crypto.Generators.RsaKeyPairGenerator();
            Key.Crypto.Parameters.RsaKeyGenerationParameters keyPairParam =
                new Key.Crypto.Parameters.RsaKeyGenerationParameters(
                    Key.Math.BigInteger.ValueOf(publicExponent), new Key.Security.SecureRandom(), strength, 25);

            // Initialise the parameters and generate the public private key pair.
            keyPair.Init(keyPairParam);
            Key.Crypto.AsymmetricCipherKeyPair rsaKeyPair = keyPair.GenerateKeyPair();

            // Assign the rsa parameters.
            RSAParameters rsaParam = new RSAParameters();

            Key.Crypto.Parameters.RsaKeyParameters           rsaPrivatePublic   = (Key.Crypto.Parameters.RsaKeyParameters)rsaKeyPair.Public;
            Key.Crypto.Parameters.RsaPrivateCrtKeyParameters rsaCrtPrivateParam = (Key.Crypto.Parameters.RsaPrivateCrtKeyParameters)rsaKeyPair.Private;

            rsaParam.D        = rsaCrtPrivateParam.Exponent.ToByteArrayUnsigned();
            rsaParam.DP       = rsaCrtPrivateParam.DP.ToByteArrayUnsigned();
            rsaParam.DQ       = rsaCrtPrivateParam.DQ.ToByteArrayUnsigned();
            rsaParam.InverseQ = rsaCrtPrivateParam.QInv.ToByteArrayUnsigned();
            rsaParam.P        = rsaCrtPrivateParam.P.ToByteArrayUnsigned();
            rsaParam.Q        = rsaCrtPrivateParam.Q.ToByteArrayUnsigned();
            rsaParam.Modulus  = rsaCrtPrivateParam.Modulus.ToByteArrayUnsigned();
            rsaParam.Exponent = rsaCrtPrivateParam.PublicExponent.ToByteArrayUnsigned();

            // Create the encyption provider.
            RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider();

            rsaProvider.ImportParameters(rsaParam);

            // Return the rsa provider.
            return(rsaProvider);
        }
Exemple #2
0
        /// <summary>
        /// The private key contained in the object.
        /// </summary>
        /// <returns>The RSA cryto service provider.</returns>
        public RSACryptoServiceProvider GetPrivateKey()
        {
            // If the pgp public key exists.
            if (_pgpSecretKey != null)
            {
                // Assign the rsa parameters.
                RSAParameters rsaPrivateParam = new RSAParameters();
                Key.Crypto.Parameters.RsaPrivateCrtKeyParameters rsaCrtPrivateParam = (Key.Crypto.Parameters.RsaPrivateCrtKeyParameters)_privateKey.Key;

                rsaPrivateParam.D        = rsaCrtPrivateParam.Exponent.ToByteArrayUnsigned();
                rsaPrivateParam.DP       = rsaCrtPrivateParam.DP.ToByteArrayUnsigned();
                rsaPrivateParam.DQ       = rsaCrtPrivateParam.DQ.ToByteArrayUnsigned();
                rsaPrivateParam.InverseQ = rsaCrtPrivateParam.QInv.ToByteArrayUnsigned();
                rsaPrivateParam.P        = rsaCrtPrivateParam.P.ToByteArrayUnsigned();
                rsaPrivateParam.Q        = rsaCrtPrivateParam.Q.ToByteArrayUnsigned();
                rsaPrivateParam.Modulus  = rsaCrtPrivateParam.Modulus.ToByteArrayUnsigned();
                rsaPrivateParam.Exponent = rsaCrtPrivateParam.PublicExponent.ToByteArrayUnsigned();

                // Create the encyption provider.
                RSACryptoServiceProvider rsaDecryptProvider = new RSACryptoServiceProvider();
                rsaDecryptProvider.ImportParameters(rsaPrivateParam);

                // Return the rsa provider.
                return(rsaDecryptProvider);
            }
            else
            {
                return(null);
            }
        }
        /// <summary>
        /// Get the RSA crypto service provider.
        /// </summary>
        /// <param name="publicPrivateKey">The stream containing the public and private key data.</param>
        /// <param name="password">The password used to decrypt the key within the file.</param>
        /// <returns>The RSA cryto service provider.</returns>
        public RSACryptoServiceProvider RSAProvider(StreamReader publicPrivateKey, string password = null)
        {
            Key.OpenSsl.PemReader keyReader = null;

            if (String.IsNullOrEmpty(password))
            {
                // Read the key file.
                keyReader = new Key.OpenSsl.PemReader(publicPrivateKey);
            }
            else
            {
                // Read the key file.
                keyReader = new Key.OpenSsl.PemReader(publicPrivateKey, new PasswordFinder(password));
            }

            // Get the ras key parameters
            Key.Crypto.AsymmetricCipherKeyPair rsaPrivateKey = (Key.Crypto.AsymmetricCipherKeyPair)keyReader.ReadObject();

            // Assign the rsa parameters.
            RSAParameters rsaParam = new RSAParameters();

            Key.Crypto.Parameters.RsaKeyParameters           rsaPrivatePublic   = (Key.Crypto.Parameters.RsaKeyParameters)rsaPrivateKey.Public;
            Key.Crypto.Parameters.RsaPrivateCrtKeyParameters rsaCrtPrivateParam = (Key.Crypto.Parameters.RsaPrivateCrtKeyParameters)rsaPrivateKey.Private;

            rsaParam.D        = rsaCrtPrivateParam.Exponent.ToByteArrayUnsigned();
            rsaParam.DP       = rsaCrtPrivateParam.DP.ToByteArrayUnsigned();
            rsaParam.DQ       = rsaCrtPrivateParam.DQ.ToByteArrayUnsigned();
            rsaParam.InverseQ = rsaCrtPrivateParam.QInv.ToByteArrayUnsigned();
            rsaParam.P        = rsaCrtPrivateParam.P.ToByteArrayUnsigned();
            rsaParam.Q        = rsaCrtPrivateParam.Q.ToByteArrayUnsigned();
            rsaParam.Modulus  = rsaCrtPrivateParam.Modulus.ToByteArrayUnsigned();
            rsaParam.Exponent = rsaCrtPrivateParam.PublicExponent.ToByteArrayUnsigned();

            // Create the encyption provider.
            RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider();

            rsaProvider.ImportParameters(rsaParam);

            // Return the rsa provider.
            return(rsaProvider);
        }
Exemple #4
0
        /// <summary>
        /// Dispose(bool disposing) executes in two distinct scenarios.
        /// If disposing equals true, the method has been called directly
        /// or indirectly by a user's code. Managed and unmanaged resources
        /// can be disposed.
        /// If disposing equals false, the method has been called by the
        /// runtime from inside the finalizer and you should not reference
        /// other objects. Only unmanaged resources can be disposed.
        /// </summary>
        protected virtual void Dispose(bool disposing)
        {
            // Check to see if Dispose has already been called.
            if (!this._disposed)
            {
                // Note disposing has been done.
                _disposed = true;

                // If disposing equals true, dispose all managed
                // and unmanaged resources.
                if (disposing)
                {
                }

                // Call the appropriate methods to clean up
                // unmanaged resources here.
                _rsPrivateParam = null;
                _certificate    = null;
                _subjectDN      = null;
            }
        }
        /// <summary>
        /// Public and secret key provider.
        /// </summary>
        /// <param name="publicKey">The public key data.</param>
        /// <param name="secretKey">The secret key data.</param>
        /// <param name="keyID">The unique key id of the public secret key pair.</param>
        /// <param name="password">The password used to protect the secret key.</param>
        /// <returns>The RSA cryto service provider.</returns>
        public RSACryptoServiceProvider PublicKeySecretKeyProvider(System.IO.Stream publicKey, System.IO.Stream secretKey, long keyID, string password = null)
        {
            // Read the public key data.
            Key.Bcpg.OpenPgp.PgpPublicKey pgpPublicKey = ReadPublicKey(publicKey);

            // Find the secret key
            Key.Bcpg.OpenPgp.PgpPrivateKey          privateKey          = null;
            Key.Bcpg.OpenPgp.PgpSecretKeyRingBundle secretKeyRingBundle =
                new Key.Bcpg.OpenPgp.PgpSecretKeyRingBundle(Key.Bcpg.OpenPgp.PgpUtilities.GetDecoderStream(secretKey));

            // Find the private key (secret key).
            privateKey = FindSecretKey(secretKeyRingBundle, keyID, password.ToArray());

            // Assign the rsa parameters.
            RSAParameters rsaPrivateParam = new RSAParameters();

            Key.Crypto.Parameters.RsaKeyParameters           rsaPrivatePublic   = (Key.Crypto.Parameters.RsaKeyParameters)pgpPublicKey.GetKey();
            Key.Crypto.Parameters.RsaPrivateCrtKeyParameters rsaCrtPrivateParam = (Key.Crypto.Parameters.RsaPrivateCrtKeyParameters)privateKey.Key;

            // Assign the rsa parameters.
            rsaPrivateParam.D        = rsaCrtPrivateParam.Exponent.ToByteArrayUnsigned();
            rsaPrivateParam.DP       = rsaCrtPrivateParam.DP.ToByteArrayUnsigned();
            rsaPrivateParam.DQ       = rsaCrtPrivateParam.DQ.ToByteArrayUnsigned();
            rsaPrivateParam.InverseQ = rsaCrtPrivateParam.QInv.ToByteArrayUnsigned();
            rsaPrivateParam.P        = rsaCrtPrivateParam.P.ToByteArrayUnsigned();
            rsaPrivateParam.Q        = rsaCrtPrivateParam.Q.ToByteArrayUnsigned();
            rsaPrivateParam.Modulus  = rsaPrivatePublic.Modulus.ToByteArrayUnsigned();
            rsaPrivateParam.Exponent = rsaPrivatePublic.Exponent.ToByteArrayUnsigned();

            // Create the encyption provider.
            RSACryptoServiceProvider rsaEncryptProvider = new RSACryptoServiceProvider();

            rsaEncryptProvider.ImportParameters(rsaPrivateParam);

            // Return the rsa provider.
            return(rsaEncryptProvider);
        }
Exemple #6
0
        /// <summary>
        /// Generate an X509 certificate.
        /// </summary>
        /// <param name="privateKey">The private key of the issuer that is signing this certificate.</param>
        /// <param name="publicKey">The public key of the issuer that is signing this certificate.</param>
        /// <param name="serialNumber">The certificate serial number.</param>
        /// <param name="issuerDN">The issuer.</param>
        /// <param name="subjectDN">The subject.</param>
        /// <param name="notBefore">Not before date.</param>
        /// <param name="notAfter">Not after data.</param>
        /// <param name="publicExponent">The public exponent (e; the public key is now represented as {e, n}).</param>
        /// <param name="strength">The strength of the cipher.</param>
        /// <param name="signatureAlgorithm">The signature algorithm to use.</param>
        /// <returns>The X509 certificate.</returns>
        public X509Certificate2 Generate(RSACryptoServiceProvider privateKey, RSACryptoServiceProvider publicKey, long serialNumber,
                                         Openssl.Subject issuerDN, Openssl.Subject subjectDN, DateTime notBefore, DateTime notAfter, long publicExponent = 3, int strength = 4096,
                                         Nequeo.Cryptography.Signing.SignatureAlgorithm signatureAlgorithm = Nequeo.Cryptography.Signing.SignatureAlgorithm.SHA512withRSA)
        {
            // Clear the certificate.
            _certificate    = null;
            _subjectDN      = subjectDN;
            _rsPrivateParam = null;

            // Create the rsa key paramaters from the strength and public exponent.
            Key.Crypto.Generators.RsaKeyPairGenerator        keyPair      = new Key.Crypto.Generators.RsaKeyPairGenerator();
            Key.Crypto.Parameters.RsaKeyGenerationParameters keyPairParam =
                new Key.Crypto.Parameters.RsaKeyGenerationParameters(
                    Key.Math.BigInteger.ValueOf(publicExponent), new Key.Security.SecureRandom(), strength, 25);

            // Initialise the parameters and generate the public private key pair.
            keyPair.Init(keyPairParam);
            Key.Crypto.AsymmetricCipherKeyPair rsaKeyPair = keyPair.GenerateKeyPair();

            // Assign the rsa parameters.
            RSAParameters rsaParam = new RSAParameters();

            Key.Crypto.Parameters.RsaKeyParameters rsaPublicParam = (Key.Crypto.Parameters.RsaKeyParameters)rsaKeyPair.Public;
            _rsPrivateParam = (Key.Crypto.Parameters.RsaPrivateCrtKeyParameters)rsaKeyPair.Private;

            rsaParam.D        = _rsPrivateParam.Exponent.ToByteArrayUnsigned();
            rsaParam.DP       = _rsPrivateParam.DP.ToByteArrayUnsigned();
            rsaParam.DQ       = _rsPrivateParam.DQ.ToByteArrayUnsigned();
            rsaParam.InverseQ = _rsPrivateParam.QInv.ToByteArrayUnsigned();
            rsaParam.P        = _rsPrivateParam.P.ToByteArrayUnsigned();
            rsaParam.Q        = _rsPrivateParam.Q.ToByteArrayUnsigned();
            rsaParam.Modulus  = _rsPrivateParam.Modulus.ToByteArrayUnsigned();
            rsaParam.Exponent = _rsPrivateParam.PublicExponent.ToByteArrayUnsigned();

            // Create the encyption provider.
            RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider();

            rsaProvider.ImportParameters(rsaParam);

            // Create a new certificate generator.
            Key.X509.X509V3CertificateGenerator certGenerator = new Key.X509.X509V3CertificateGenerator();
            certGenerator.Reset();

            // Set the certificate values.
            certGenerator.SetSerialNumber(Key.Math.BigInteger.ValueOf(serialNumber));
            certGenerator.SetIssuerDN(GetNames(issuerDN));
            certGenerator.SetSubjectDN(GetNames(subjectDN));
            certGenerator.SetNotBefore(notBefore);
            certGenerator.SetNotAfter(notAfter);
            certGenerator.SetPublicKey(rsaPublicParam);
            certGenerator.SetSignatureAlgorithm(GetSignatureAlgorithm(signatureAlgorithm));

            // Export the signer private key parameters.
            RSAParameters rsaPrivateKeySignerParam = privateKey.ExportParameters(true);

            Key.Crypto.Parameters.RsaPrivateCrtKeyParameters rsaPrivateKeySigner =
                new Key.Crypto.Parameters.RsaPrivateCrtKeyParameters(
                    new Key.Math.BigInteger(1, rsaPrivateKeySignerParam.Modulus),
                    new Key.Math.BigInteger(1, rsaPrivateKeySignerParam.Exponent),
                    new Key.Math.BigInteger(1, rsaPrivateKeySignerParam.D),
                    new Key.Math.BigInteger(1, rsaPrivateKeySignerParam.P),
                    new Key.Math.BigInteger(1, rsaPrivateKeySignerParam.Q),
                    new Key.Math.BigInteger(1, rsaPrivateKeySignerParam.DP),
                    new Key.Math.BigInteger(1, rsaPrivateKeySignerParam.DQ),
                    new Key.Math.BigInteger(1, rsaPrivateKeySignerParam.InverseQ)
                    );

            // Export the signer public key parameters.
            RSAParameters rsaPublicKeySignerParam = publicKey.ExportParameters(false);

            Key.Crypto.Parameters.RsaKeyParameters rsaPublicKeySigner =
                new Key.Crypto.Parameters.RsaKeyParameters(
                    false,
                    new Key.Math.BigInteger(1, rsaPublicKeySignerParam.Modulus),
                    new Key.Math.BigInteger(1, rsaPublicKeySignerParam.Exponent)
                    );

            // Add the extensions
            certGenerator.AddExtension(
                Key.Asn1.X509.X509Extensions.SubjectKeyIdentifier,
                false,
                new Key.X509.Extension.SubjectKeyIdentifierStructure(rsaPublicParam));

            certGenerator.AddExtension(
                Key.Asn1.X509.X509Extensions.AuthorityKeyIdentifier,
                false,
                new Key.X509.Extension.AuthorityKeyIdentifierStructure(rsaPublicKeySigner));

            // Create the certificate.
            _certificate = certGenerator.Generate(rsaPrivateKeySigner);
            _certificate.CheckValidity(DateTime.UtcNow);
            _certificate.Verify(rsaPublicKeySigner);
            byte[] raw = _certificate.GetEncoded();

            // Return the certificate.
            X509Certificate2 x509Certificate2 = new X509Certificate2(raw);

            x509Certificate2.PrivateKey   = rsaProvider;
            x509Certificate2.FriendlyName = subjectDN.CommonName;
            return(x509Certificate2);
        }
Exemple #7
0
        /// <summary>
        /// Generate a public secret key pair.
        /// </summary>
        /// <param name="publicKey">The stream where public key data is written to.</param>
        /// <param name="secretKey">The stream where secret key data is written to.</param>
        /// <param name="identity">The unique identity of the public secret key pair (Name (comments) &lt;[email protected]&gt;).</param>
        /// <param name="password">The password used to protect the secret key.</param>
        /// <param name="isCritical">True, if should be treated as critical, false otherwise.</param>
        /// <param name="secondsKeyValid">The number of seconds the key is valid, or zero if no expiry.</param>
        /// <param name="secondsSignatureValid">The number of seconds the signature is valid, or zero if no expiry.</param>
        /// <param name="protectedKeys">Should the public and secret key data be protected.</param>
        /// <param name="publicExponent">The public exponent (e; the public key is now represented as {e, n}).</param>
        /// <param name="strength">The strength of the cipher.</param>
        /// <param name="hashAlgorithm">The preferred hash algorithm to use to create the hash value.</param>
        /// <param name="publicKeyAlgorithm">The public key algorithm type.</param>
        /// <param name="certificateLevel">The certification level.</param>
        /// <param name="symmetricKeyAlgorithm">The symmetric key algorithm used for cryptography.</param>
        /// <returns>The unique key id of the public secret key pair.</returns>
        public long Generate(System.IO.Stream publicKey, System.IO.Stream secretKey, Openpgp.Identity identity,
                             string password, bool isCritical = false, long secondsKeyValid = 0, long secondsSignatureValid = 0,
                             bool protectedKeys = true, long publicExponent = 3, int strength = 4096, Nequeo.Cryptography.HashcodeType hashAlgorithm = HashcodeType.SHA512,
                             Openpgp.PublicKeyAlgorithmType publicKeyAlgorithm = Openpgp.PublicKeyAlgorithmType.RsaGeneral,
                             Openpgp.CertificateLevelType certificateLevel     = Openpgp.CertificateLevelType.DefaultCertification,
                             Nequeo.Cryptography.SymmetricKeyAlgorithmType symmetricKeyAlgorithm = Nequeo.Cryptography.SymmetricKeyAlgorithmType.Aes256)
        {
            // Create the rsa key paramaters from the strength and public exponent.
            Key.Crypto.Generators.RsaKeyPairGenerator        keyPair      = new Key.Crypto.Generators.RsaKeyPairGenerator();
            Key.Crypto.Parameters.RsaKeyGenerationParameters keyPairParam =
                new Key.Crypto.Parameters.RsaKeyGenerationParameters(
                    Key.Math.BigInteger.ValueOf(publicExponent), new Key.Security.SecureRandom(), strength, 25);

            // Initialise the parameters and generate the public private key pair.
            keyPair.Init(keyPairParam);
            Key.Crypto.AsymmetricCipherKeyPair rsaKeyPair = keyPair.GenerateKeyPair();

            // Seperate the keys.
            Key.Crypto.Parameters.RsaKeyParameters           rsaPrivatePublic   = (Key.Crypto.Parameters.RsaKeyParameters)rsaKeyPair.Public;
            Key.Crypto.Parameters.RsaPrivateCrtKeyParameters rsaCrtPrivateParam = (Key.Crypto.Parameters.RsaPrivateCrtKeyParameters)rsaKeyPair.Private;

            // If file is not protected.
            if (!protectedKeys)
            {
                secretKey = new Key.Bcpg.ArmoredOutputStream(secretKey);
            }

            // Create the signature subpackets.
            Key.Bcpg.OpenPgp.PgpSignatureSubpacketGenerator signatureSubpacketGenerator = new Key.Bcpg.OpenPgp.PgpSignatureSubpacketGenerator();
            signatureSubpacketGenerator.SetKeyExpirationTime(isCritical, secondsKeyValid);
            signatureSubpacketGenerator.SetPreferredHashAlgorithms(isCritical, new int[] { (int)Openpgp.PublicSecretKey.GetHashAlgorithm(hashAlgorithm) });
            signatureSubpacketGenerator.SetSignatureExpirationTime(isCritical, secondsSignatureValid);

            // Create the signature subpackets.
            Key.Bcpg.OpenPgp.PgpSignatureSubpacketGenerator signatureSubpacketUnHashedGenerator = new Key.Bcpg.OpenPgp.PgpSignatureSubpacketGenerator();
            signatureSubpacketUnHashedGenerator.SetKeyExpirationTime(isCritical, secondsKeyValid);
            signatureSubpacketUnHashedGenerator.SetPreferredHashAlgorithms(isCritical, new int[] { (int)Openpgp.PublicSecretKey.GetHashAlgorithm(hashAlgorithm) });
            signatureSubpacketUnHashedGenerator.SetSignatureExpirationTime(isCritical, secondsSignatureValid);

            // Generate the packets
            Key.Bcpg.OpenPgp.PgpSignatureSubpacketVector hashedPackets   = signatureSubpacketGenerator.Generate();
            Key.Bcpg.OpenPgp.PgpSignatureSubpacketVector unhashedPackets = signatureSubpacketUnHashedGenerator.Generate();

            // Create the secret key.
            Key.Bcpg.OpenPgp.PgpSecretKey pgpSecretKey = new Key.Bcpg.OpenPgp.PgpSecretKey
                                                         (
                GetCertificateLevelType(certificateLevel),
                GetPublicKeyAlgorithm(publicKeyAlgorithm),
                rsaPrivatePublic,
                rsaCrtPrivateParam,
                DateTime.UtcNow,
                identity.ToString(),
                Openpgp.PublicSecretKey.GetSymmetricKeyAlgorithm(symmetricKeyAlgorithm),
                password.ToArray(),
                true,
                hashedPackets,
                unhashedPackets,
                new Key.Security.SecureRandom(),
                Openpgp.PublicSecretKey.GetHashAlgorithm(hashAlgorithm)
                                                         );

            // Encode the secret key.
            pgpSecretKey.Encode(secretKey);

            // If file is not protected.
            if (!protectedKeys)
            {
                secretKey.Close();
                publicKey = new Key.Bcpg.ArmoredOutputStream(publicKey);
            }

            // Get the public key from the secret key.
            Key.Bcpg.OpenPgp.PgpPublicKey pgpPublicKey = pgpSecretKey.PublicKey;
            pgpPublicKey.Encode(publicKey);

            // If file is not protected.
            if (!protectedKeys)
            {
                publicKey.Close();
            }

            // Return the key id.
            return(pgpSecretKey.KeyId);
        }
Exemple #8
0
        /// <summary>
        /// Generate a public secret key pair RSA crypto service provider.
        /// </summary>
        /// <param name="publicKey">The stream where public key data is written to.</param>
        /// <param name="secretKey">The stream where secret key data is written to.</param>
        /// <param name="identity">The unique identity of the public secret key pair (Name (comments) &lt;[email protected]&gt;).</param>
        /// <param name="password">The password used to protect the secret key.</param>
        /// <param name="keyID">The unique key id of the public secret key pair.</param>
        /// <param name="isCritical">True, if should be treated as critical, false otherwise.</param>
        /// <param name="secondsKeyValid">The number of seconds the key is valid, or zero if no expiry.</param>
        /// <param name="secondsSignatureValid">The number of seconds the signature is valid, or zero if no expiry.</param>
        /// <param name="protectedKeys">Should the public and secret key data be protected.</param>
        /// <param name="publicExponent">The public exponent (e; the public key is now represented as {e, n}).</param>
        /// <param name="strength">The strength of the cipher.</param>
        /// <param name="hashAlgorithm">The preferred hash algorithm to use to create the hash value.</param>
        /// <param name="symmetricKeyAlgorithm">The symmetric key algorithm used for cryptography.</param>
        /// <returns>The RSA cryto service provider.</returns>
        public RSACryptoServiceProvider Generate(System.IO.Stream publicKey, System.IO.Stream secretKey, string identity, string password,
                                                 out long keyID, bool isCritical = false, long secondsKeyValid = 0, long secondsSignatureValid = 0,
                                                 bool protectedKeys = true, long publicExponent = 3, int strength = 4096,
                                                 Nequeo.Cryptography.HashcodeType hashAlgorithm = HashcodeType.SHA512,
                                                 Nequeo.Cryptography.SymmetricKeyAlgorithmType symmetricKeyAlgorithm = Nequeo.Cryptography.SymmetricKeyAlgorithmType.Aes256)
        {
            // Create the rsa key paramaters from the strength and public exponent.
            Key.Crypto.Generators.RsaKeyPairGenerator        keyPair      = new Key.Crypto.Generators.RsaKeyPairGenerator();
            Key.Crypto.Parameters.RsaKeyGenerationParameters keyPairParam =
                new Key.Crypto.Parameters.RsaKeyGenerationParameters(
                    Key.Math.BigInteger.ValueOf(publicExponent), new Key.Security.SecureRandom(), strength, 25);

            // Initialise the parameters and generate the public private key pair.
            keyPair.Init(keyPairParam);
            Key.Crypto.AsymmetricCipherKeyPair rsaKeyPair = keyPair.GenerateKeyPair();

            // Seperate the keys.
            Key.Crypto.Parameters.RsaKeyParameters           rsaPrivatePublic   = (Key.Crypto.Parameters.RsaKeyParameters)rsaKeyPair.Public;
            Key.Crypto.Parameters.RsaPrivateCrtKeyParameters rsaCrtPrivateParam = (Key.Crypto.Parameters.RsaPrivateCrtKeyParameters)rsaKeyPair.Private;

            // If file is not protected.
            if (!protectedKeys)
            {
                secretKey = new Key.Bcpg.ArmoredOutputStream(secretKey);
            }

            // Create the signature subpackets.
            Key.Bcpg.OpenPgp.PgpSignatureSubpacketGenerator signatureSubpacketGenerator = new Key.Bcpg.OpenPgp.PgpSignatureSubpacketGenerator();
            signatureSubpacketGenerator.SetKeyExpirationTime(isCritical, secondsKeyValid);
            signatureSubpacketGenerator.SetPreferredHashAlgorithms(isCritical, new int[] { (int)GetHashAlgorithm(hashAlgorithm) });
            signatureSubpacketGenerator.SetSignatureExpirationTime(isCritical, secondsSignatureValid);

            // Create the signature subpackets.
            Key.Bcpg.OpenPgp.PgpSignatureSubpacketGenerator signatureSubpacketUnHashedGenerator = new Key.Bcpg.OpenPgp.PgpSignatureSubpacketGenerator();
            signatureSubpacketUnHashedGenerator.SetKeyExpirationTime(isCritical, secondsKeyValid);
            signatureSubpacketUnHashedGenerator.SetPreferredHashAlgorithms(isCritical, new int[] { (int)GetHashAlgorithm(hashAlgorithm) });
            signatureSubpacketUnHashedGenerator.SetSignatureExpirationTime(isCritical, secondsSignatureValid);

            // Generate the packets
            Key.Bcpg.OpenPgp.PgpSignatureSubpacketVector hashedPackets   = signatureSubpacketGenerator.Generate();
            Key.Bcpg.OpenPgp.PgpSignatureSubpacketVector unhashedPackets = signatureSubpacketUnHashedGenerator.Generate();

            // Create the secret key.
            Key.Bcpg.OpenPgp.PgpSecretKey pgpSecretKey = new Key.Bcpg.OpenPgp.PgpSecretKey
                                                         (
                Key.Bcpg.OpenPgp.PgpSignature.DefaultCertification,
                Key.Bcpg.PublicKeyAlgorithmTag.RsaGeneral,
                rsaPrivatePublic,
                rsaCrtPrivateParam,
                DateTime.UtcNow,
                identity,
                GetSymmetricKeyAlgorithm(symmetricKeyAlgorithm),
                password.ToArray(),
                true,
                hashedPackets,
                unhashedPackets,
                new Key.Security.SecureRandom(),
                GetHashAlgorithm(hashAlgorithm)
                                                         );

            // Encode the secret key.
            pgpSecretKey.Encode(secretKey);

            // If file is not protected.
            if (!protectedKeys)
            {
                secretKey.Close();
                publicKey = new Key.Bcpg.ArmoredOutputStream(publicKey);
            }

            // Get the public key from the secret key.
            Key.Bcpg.OpenPgp.PgpPublicKey pgpPublicKey = pgpSecretKey.PublicKey;
            pgpPublicKey.Encode(publicKey);

            // If file is not protected.
            if (!protectedKeys)
            {
                publicKey.Close();
            }

            // Assign the rsa parameters.
            RSAParameters rsaParam = new RSAParameters();

            rsaParam.D        = rsaCrtPrivateParam.Exponent.ToByteArrayUnsigned();
            rsaParam.DP       = rsaCrtPrivateParam.DP.ToByteArrayUnsigned();
            rsaParam.DQ       = rsaCrtPrivateParam.DQ.ToByteArrayUnsigned();
            rsaParam.InverseQ = rsaCrtPrivateParam.QInv.ToByteArrayUnsigned();
            rsaParam.P        = rsaCrtPrivateParam.P.ToByteArrayUnsigned();
            rsaParam.Q        = rsaCrtPrivateParam.Q.ToByteArrayUnsigned();
            rsaParam.Modulus  = rsaCrtPrivateParam.Modulus.ToByteArrayUnsigned();
            rsaParam.Exponent = rsaCrtPrivateParam.PublicExponent.ToByteArrayUnsigned();

            // Create the encyption provider.
            RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider();

            rsaProvider.ImportParameters(rsaParam);

            // Return the rsa provider.
            keyID = pgpSecretKey.KeyId;
            return(rsaProvider);
        }
Exemple #9
0
        /// <summary>
        /// Computes the hash value of the specified input stream using the specified
        /// hash algorithm, and signs the resulting hash value.
        /// </summary>
        /// <param name="inputStream">The input data for which to compute the hash.</param>
        /// <param name="rsaProvider">The RSA crypto service provider.</param>
        /// <param name="keyID">The unique key id of the public secret key pair.</param>
        /// <param name="hashAlgorithm">The hash algorithm to use to create the hash value.</param>
        /// <returns>The signature for the specified data.</returns>
        public byte[] SignData(Stream inputStream, RSACryptoServiceProvider rsaProvider, long keyID, Nequeo.Cryptography.HashcodeType hashAlgorithm = HashcodeType.SHA512)
        {
            MemoryStream output = null;

            Key.Bcpg.BcpgOutputStream pgpOutput = null;

            try
            {
                int ch;
                output = new MemoryStream();

                // Export the signer private key parameters.
                RSAParameters rsaPrivateKeySignerParam = rsaProvider.ExportParameters(true);
                Key.Crypto.Parameters.RsaPrivateCrtKeyParameters rsaPrivateKeySigner =
                    new Key.Crypto.Parameters.RsaPrivateCrtKeyParameters(
                        new Key.Math.BigInteger(1, rsaPrivateKeySignerParam.Modulus),
                        new Key.Math.BigInteger(1, rsaPrivateKeySignerParam.Exponent),
                        new Key.Math.BigInteger(1, rsaPrivateKeySignerParam.D),
                        new Key.Math.BigInteger(1, rsaPrivateKeySignerParam.P),
                        new Key.Math.BigInteger(1, rsaPrivateKeySignerParam.Q),
                        new Key.Math.BigInteger(1, rsaPrivateKeySignerParam.DP),
                        new Key.Math.BigInteger(1, rsaPrivateKeySignerParam.DQ),
                        new Key.Math.BigInteger(1, rsaPrivateKeySignerParam.InverseQ)
                        );

                // Get the private key.
                Key.Bcpg.OpenPgp.PgpPrivateKey privateKey = new Key.Bcpg.OpenPgp.PgpPrivateKey(rsaPrivateKeySigner, keyID);

                // Create a signature generator.
                Key.Bcpg.OpenPgp.PgpSignatureGenerator signatureGenerator =
                    new Key.Bcpg.OpenPgp.PgpSignatureGenerator(Key.Bcpg.PublicKeyAlgorithmTag.RsaGeneral, GetHashAlgorithm(hashAlgorithm));
                signatureGenerator.InitSign(Key.Bcpg.OpenPgp.PgpSignature.BinaryDocument, privateKey);

                // Create the output stream.
                pgpOutput = new Key.Bcpg.BcpgOutputStream(output);

                // Read the input stream.
                while ((ch = inputStream.ReadByte()) >= 0)
                {
                    // Update the generator.
                    signatureGenerator.Update((byte)ch);
                }

                // Write the hash to the output stream.
                Key.Bcpg.OpenPgp.PgpSignature signature = signatureGenerator.Generate();
                signature.Encode(pgpOutput);

                // Return the signed value.
                return(output.ToArray());
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (output != null)
                {
                    output.Close();
                }

                if (pgpOutput != null)
                {
                    pgpOutput.Close();
                }
            }
        }