byte[] EncryptAsymmetricKeyParameter(AsymmetricKeyParameter key)
        {
            var cipher  = PbeUtilities.CreateEngine(EncryptionAlgorithm.Id) as IBufferedCipher;
            var keyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(key);
            var random  = new SecureRandom();
            var salt    = new byte[SaltSize];

            if (cipher == null)
            {
                throw new Exception("Unknown encryption algorithm: " + EncryptionAlgorithm.Id);
            }

            random.NextBytes(salt);

            var pbeParameters    = PbeUtilities.GenerateAlgorithmParameters(EncryptionAlgorithm.Id, salt, MinIterations);
            var algorithm        = new AlgorithmIdentifier(EncryptionAlgorithm, pbeParameters);
            var cipherParameters = PbeUtilities.GenerateCipherParameters(algorithm, passwd);

            if (cipherParameters == null)
            {
                throw new Exception("BouncyCastle bug detected: Failed to generate cipher parameters.");
            }

            cipher.Init(true, cipherParameters);

            var encoded = cipher.DoFinal(keyInfo.GetEncoded());

            var encrypted = new EncryptedPrivateKeyInfo(algorithm, encoded);

            return(encrypted.GetEncoded());
        }
예제 #2
0
        public PemObject Generate()
        {
            if (algorithm == null)
            {
                PrivateKeyInfo pki = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privKey);

                return(new PemObject("PRIVATE KEY", pki.GetEncoded()));
            }

            // TODO Theoretically, the amount of salt needed depends on the algorithm
            byte[] salt = new byte[20];
            if (random == null)
            {
                random = new SecureRandom();
            }
            random.NextBytes(salt);

            try
            {
                EncryptedPrivateKeyInfo epki = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo(
                    algorithm, password, salt, iterationCount, privKey);

                return(new PemObject("ENCRYPTED PRIVATE KEY", epki.GetEncoded()));
            }
            catch (Exception e)
            {
                throw new PemGenerationException("Couldn't encrypt private key", e);
            }
        }
예제 #3
0
        public PemObject Generate()
        {
            if (this.algorithm == null)
            {
                PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(this.privKey);
                return(new PemObject("PRIVATE KEY", privateKeyInfo.GetEncoded()));
            }
            byte[] array = new byte[20];
            if (this.random == null)
            {
                this.random = new SecureRandom();
            }
            this.random.NextBytes(array);
            PemObject result;

            try
            {
                EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo(this.algorithm, this.password, array, this.iterationCount, this.privKey);
                result = new PemObject("ENCRYPTED PRIVATE KEY", encryptedPrivateKeyInfo.GetEncoded());
            }
            catch (Exception exception)
            {
                throw new PemGenerationException("Couldn't encrypt private key", exception);
            }
            return(result);
        }
예제 #4
0
 public PemObject Generate()
 {
     if (algorithm == null)
     {
         PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privKey);
         return(new PemObject("PRIVATE KEY", privateKeyInfo.GetEncoded()));
     }
     byte[] array = new byte[20];
     if (random == null)
     {
         random = new SecureRandom();
     }
     ((Random)random).NextBytes(array);
     try
     {
         EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo(algorithm, password, array, iterationCount, privKey);
         return(new PemObject("ENCRYPTED PRIVATE KEY", encryptedPrivateKeyInfo.GetEncoded()));
     }
     catch (global::System.Exception exception)
     {
         throw new PemGenerationException("Couldn't encrypt private key", exception);
     }
 }
 /// <summary>
 /// Return a binary ASN.1 encoding of the EncryptedPrivateKeyInfo structure in this object.
 /// </summary>
 /// <returns>A byte array containing the encoded object.</returns>
 public byte[] GetEncoded()
 {
     return(encryptedPrivateKeyInfo.GetEncoded());
 }
        private static string EncryptPrivateKey(AsymmetricKeyParameter privateKey, string password)
        {
            // Create salts
            byte[]       aesIv     = new byte[16];
            byte[]       keySalt   = new byte[20];
            SecureRandom randomGen = new SecureRandom();

            randomGen.NextBytes(aesIv);
            randomGen.NextBytes(keySalt);
            try {
                PrivateKeyInfo decryptedPrivateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey);

                // Prepare encryption
                Pkcs5S2ParametersGenerator pkcs5S2Gen = new Pkcs5S2ParametersGenerator();
                pkcs5S2Gen.Init(PKCS5PasswordToBytes(password.ToCharArray()), keySalt, hashIterationCount);
                ICipherParameters cipherParams = pkcs5S2Gen.GenerateDerivedParameters(NistObjectIdentifiers.IdAes256Cbc.Id, 256);
                IBufferedCipher   cipher       = CipherUtilities.GetCipher(NistObjectIdentifiers.IdAes256Cbc);
                cipher.Init(true, new ParametersWithIV(cipherParams, aesIv));

                // Generate encrypted private key info
                Asn1OctetString     aesIvOctetString = new DerOctetString(aesIv);
                KeyDerivationFunc   keyFunction      = new KeyDerivationFunc(PkcsObjectIdentifiers.IdPbkdf2, new Pbkdf2Params(keySalt, hashIterationCount));
                EncryptionScheme    encScheme        = new EncryptionScheme(NistObjectIdentifiers.IdAes256Cbc, aesIvOctetString);
                Asn1EncodableVector encryptionInfo   = new Asn1EncodableVector {
                    keyFunction, encScheme
                };
                AlgorithmIdentifier     algIdentifier                   = new AlgorithmIdentifier(PkcsObjectIdentifiers.IdPbeS2, new DerSequence(encryptionInfo));
                EncryptedPrivateKeyInfo encryptedPrivateKeyInfo         = new EncryptedPrivateKeyInfo(algIdentifier, cipher.DoFinal(decryptedPrivateKeyInfo.GetEncoded()));
                Org.BouncyCastle.Utilities.IO.Pem.PemObject pkPemObject = new Org.BouncyCastle.Utilities.IO.Pem.PemObject("ENCRYPTED PRIVATE KEY", encryptedPrivateKeyInfo.GetEncoded());

                // Write the PEM object to a string
                StringWriter txtWriter = new StringWriter();
                PemWriter    pemWriter = new PemWriter(txtWriter);
                pemWriter.WriteObject(pkPemObject);
                pemWriter.Writer.Close();
                return(txtWriter.ToString());
            } catch (Exception e) {
                throw new CryptoException("Could not encrypt private key.", e);
            }
        }