internal SecretKeyDecryptor(SymmetricKeyAlgorithmTag symAlg, byte[] key, byte[] iv, S2k s2k, IDigestFactory <PgpDigestTypeIdentifier> checksumCalculatorFactory)
            {
                FipsTripleDes.ParametersWithIV parameters;

                parameters = FipsTripleDes.Cfb64.WithIV(iv);


                this.s2k      = s2k;
                cipherBuilder = CryptoServicesRegistrar.CreateService(new FipsTripleDes.Key(key)).CreateDecryptorBuilder(FipsTripleDes.Cfb64.WithIV(iv));
            }
        /// <summary>
        /// Add a set of SafeBags that are to be wrapped in a EncryptedData object.
        /// </summary>
        /// <param name="dataEncryptor">The encryptor to use for encoding the data.</param>
        /// <param name="data">the SafeBags to include.</param>
        /// <returns>this builder.</returns>
        public Pkcs12PfxPduBuilder AddEncryptedData(ICipherBuilder <AlgorithmIdentifier> dataEncryptor, Pkcs12SafeBag[] data)
        {
            Asn1EncodableVector v = new Asn1EncodableVector();

            for (int i = 0; i != data.Length; i++)
            {
                v.Add(data[i].ToAsn1Structure());
            }

            return(addEncryptedData(dataEncryptor, new DerSequence(v)));
        }
        private Pkcs12PfxPduBuilder addEncryptedData(ICipherBuilder <AlgorithmIdentifier> dataEncryptor, Asn1Sequence data)
        {
            CmsEncryptedDataGenerator envGen = new CmsEncryptedDataGenerator();

            try
            {
                dataVector.Add(envGen.generate(new CmsProcessableByteArray(data.GetEncoded()), dataEncryptor).ToAsn1Structure());
            }
            catch (CmsException e)
            {
                throw new PkcsIOException(e.Message, e.InnerException);
            }

            return(this);
        }
        private CmsEncryptedData doGenerate(
            ICmsTypedData content,
            ICipherBuilder <AlgorithmIdentifier> contentEncryptor)
        {
            AlgorithmIdentifier encAlgId;
            Asn1OctetString     encContent;

            MemoryOutputStream bOut = new MemoryOutputStream();

            try
            {
                ICipher cipher = contentEncryptor.BuildCipher(bOut);

                content.Write(cipher.Stream);

                cipher.Stream.Close();
            }
            catch (IOException)
            {
                throw new CmsException("");
            }

            byte[] encryptedContent = bOut.ToArray();

            encAlgId = contentEncryptor.AlgorithmDetails;

            encContent = new BerOctetString(encryptedContent);

            EncryptedContentInfo eci = new EncryptedContentInfo(
                content.ContentType,
                encAlgId,
                encContent);

            Asn1Set unprotectedAttrSet = null;

            if (unprotectedAttributeGenerator != null)
            {
                Asn1.Cms.AttributeTable attrTable = unprotectedAttributeGenerator.GetAttributes(new Dictionary <string, object>());

                unprotectedAttrSet = new BerSet(attrTable.ToAsn1EncodableVector());
            }

            ContentInfo contentInfo = new ContentInfo(
                CmsObjectIdentifiers.EncryptedData,
                new EncryptedData(eci, unprotectedAttrSet));

            return(new CmsEncryptedData(contentInfo));
        }
Exemple #5
0
        /// <summary>
        /// Encode and encrypt the passed in object and write it in PEM format.
        /// </summary>
        /// <param name="obj">The object to be encoded and encrypted.</param>
        /// <param name="encryptor">The PEM encryptor to use.</param>
        public void WriteObject(object obj, ICipherBuilder <DekInfo> encryptor)
        {
            try
            {
                base.WriteObject(new MiscPemGenerator(obj, encryptor));
            }
            catch (PemGenerationException e)
            {
                if (e.InnerException is IOException)
                {
                    throw e.InnerException;
                }

                throw e;
            }
        }
        public CmsTypedStream GetContentStream(IDecryptorBuilderProvider <AlgorithmIdentifier> inputDecryptorProvider)
        {
            try
            {
                EncryptedContentInfo encContentInfo = encryptedData.EncryptedContentInfo;
                ICipherBuilder <AlgorithmIdentifier> decryptorBuilder = inputDecryptorProvider.CreateDecryptorBuilder(encContentInfo.ContentEncryptionAlgorithm);

                MemoryInputStream encIn = new MemoryInputStream(encContentInfo.EncryptedContent.GetOctets());

                ICipher cipher = decryptorBuilder.BuildCipher(encIn);

                return(new CmsTypedStream(encContentInfo.ContentType, cipher.Stream));
            }
            catch (Exception e)
            {
                throw new CmsException("unable to create stream: " + e.Message, e);
            }
        }
        /// <summary>
        /// Get a decryptor from the passed in provider and decrypt the encrypted private key info, returning the result.
        /// </summary>
        /// <param name="inputDecryptorProvider">A provider to query for decryptors for the object.</param>
        /// <returns>The decrypted private key info structure.</returns>
        public PrivateKeyInfo DecryptPrivateKeyInfo(IDecryptorBuilderProvider inputDecryptorProvider)
        {
            try
            {
                ICipherBuilder decryptorBuilder = inputDecryptorProvider.CreateDecryptorBuilder(encryptedPrivateKeyInfo.EncryptionAlgorithm);

                ICipher encIn = decryptorBuilder.BuildCipher(new MemoryInputStream(encryptedPrivateKeyInfo.GetEncryptedData()));

                Stream strm = encIn.Stream;
                byte[] data = Streams.ReadAll(encIn.Stream);
                Platform.Dispose(strm);

                return(PrivateKeyInfo.GetInstance(data));
            }
            catch (Exception e)
            {
                throw new PkcsException("unable to read encrypted data: " + e.Message, e);
            }
        }
        /// <summary>
        /// Create the encrypted private key info using the passed in encryptor.
        /// </summary>
        /// <param name="encryptor">The encryptor to use.</param>
        /// <returns>An encrypted private key info containing the original private key info.</returns>
        public Pkcs8EncryptedPrivateKeyInfo Build(
            ICipherBuilder encryptor)
        {
            try
            {
                MemoryStream bOut    = new MemoryOutputStream();
                ICipher      cOut    = encryptor.BuildCipher(bOut);
                byte[]       keyData = privateKeyInfo.GetEncoded();

                Stream str = cOut.Stream;
                str.Write(keyData, 0, keyData.Length);
                BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(str);

                return(new Pkcs8EncryptedPrivateKeyInfo(new EncryptedPrivateKeyInfo((AlgorithmIdentifier)encryptor.AlgorithmDetails, bOut.ToArray())));
            }
            catch (IOException)
            {
                throw new InvalidOperationException("cannot encode privateKeyInfo");
            }
        }
        /// <summary>
        /// Create the encrypted private key info using the passed in encryptor.
        /// </summary>
        /// <param name="encryptor">The encryptor to use.</param>
        /// <returns>An encrypted private key info containing the original private key info.</returns>
        public Pkcs8EncryptedPrivateKeyInfo Build(
            ICipherBuilder encryptor)
        {
            try
            {
                MemoryStream bOut    = new MemoryOutputStream();
                ICipher      cOut    = encryptor.BuildCipher(bOut);
                byte[]       keyData = privateKeyInfo.GetEncoded();

                using (var str = cOut.Stream)
                {
                    str.Write(keyData, 0, keyData.Length);
                }

                return(new Pkcs8EncryptedPrivateKeyInfo(new EncryptedPrivateKeyInfo((AlgorithmIdentifier)encryptor.AlgorithmDetails, bOut.ToArray())));
            }
            catch (IOException)
            {
                throw new InvalidOperationException("cannot encode privateKeyInfo");
            }
        }
        public PkixContentEncryptor(DerObjectIdentifier encAlgorithm, SecureRandom random)
        {
            key = keyGenerators[encAlgorithm](random);

            algId = Utils.GetEncryptionSchemeIdentifier(encAlgorithm, random);

            IParameters <Algorithm> cipherParams = Utils.GetCipherParameters(algId);

            if (Utils.IsBlockMode(cipherParams.Algorithm))
            {
                cipherBuilder = new PkixBlockCipherBuilder(algId, Utils.CreateBlockEncryptorBuilder(encAlgorithm, key.GetKeyBytes(), cipherParams));
            }
            else if (Utils.IsAeadMode(cipherParams.Algorithm))
            {
                cipherBuilder = new PkixAeadCipherBuilder(algId, Utils.CreateAeadEncryptorBuilder(encAlgorithm, key.GetKeyBytes(), cipherParams));
            }
            else
            {
                cipherBuilder = new PkixCipherBuilder(algId, Utils.CreateEncryptorBuilder(encAlgorithm, key.GetKeyBytes(), cipherParams));
            }
        }
Exemple #11
0
        public object Decrypt(IDecryptorBuilderProvider <DekInfo> keyDecryptorProvider)
        {
            try
            {
                ICipherBuilder <DekInfo> decryptorBuilder = keyDecryptorProvider.CreateDecryptorBuilder(new DekInfo(dekInfo));

                MemoryInputStream bOut      = new MemoryInputStream(keyBytes);
                ICipher           decryptor = decryptorBuilder.BuildCipher(bOut);

                using (var stream = decryptor.Stream)
                {
                    return(parser.Parse(Streams.ReadAll(stream)));
                }
            }
            catch (IOException e)
            {
                throw e;
            }
            catch (Exception e)
            {
                throw new OpenSslPemParsingException("exception processing key pair: " + e.Message, e);
            }
        }
Exemple #12
0
            internal SecretKeyEncryptor(SymmetricKeyAlgorithmTag symAlg, byte[] key, byte[] iv, S2k s2k, IDigestFactory <PgpDigestTypeIdentifier> checksumCalculatorFactory)
            {
                FipsTripleDes.ParametersWithIV parameters;
                if (iv != null)
                {
                    parameters = FipsTripleDes.Cfb64.WithIV(iv);
                    this.iv    = iv;
                }
                else
                {
                    if (this.random == null)
                    {
                        this.random = new SecureRandom();
                    }

                    parameters = FipsTripleDes.Cfb64.WithIV(random);

                    this.iv = parameters.GetIV();
                }
                this.s2k = s2k;

                cipherBuilder = CryptoServicesRegistrar.CreateService(new FipsTripleDes.Key(key)).CreateEncryptorBuilder(FipsTripleDes.Cfb64.WithIV(iv));
            }
        internal static ICipherBuilder <DekInfo> Crypt(
            bool encrypt,
            char[] password,
            String dekAlgName,
            byte[] iv)
        {
            byte[] ivValue   = iv;
            String blockMode = "CBC";

            byte[] sKey;
            IBlockCipherService cipherService = null;
            IBlockCipherBuilder <IParameters <Algorithm> > blockCipherBuilder = null;
            ICipherBuilder <IParameters <Algorithm> >      cipherBuilder      = null;

            DekInfo dekInfo;

            if (iv != null && iv.Length != 0)
            {
                dekInfo = new DekInfo(dekAlgName + "," + Hex.ToHexString(iv));
            }
            else
            {
                dekInfo = new DekInfo(dekAlgName);
            }
            // Figure out block mode and padding.
            if (dekAlgName.EndsWith("-CFB"))
            {
                blockMode = "CFB";
            }
            if (dekAlgName.EndsWith("-ECB") ||
                "DES-EDE".Equals(dekAlgName) ||
                "DES-EDE3".Equals(dekAlgName))
            {
                // ECB is actually the default (though seldom used) when OpenSSL
                // uses DES-EDE (des2) or DES-EDE3 (des3).
                blockMode = "ECB";
            }
            if (dekAlgName.EndsWith("-OFB"))
            {
                blockMode = "OFB";
            }

            // Figure out algorithm and key size.
            if (dekAlgName.StartsWith("DES-EDE"))
            {
                // "DES-EDE" is actually des2 in OpenSSL-speak!
                // "DES-EDE3" is des3.
                bool des2 = !dekAlgName.StartsWith("DES-EDE3");

                FipsTripleDes.Key tdesKey = new FipsTripleDes.Key(getKey(password, 24, iv, des2));
                cipherService = CryptoServicesRegistrar.CreateService(tdesKey);

                if (blockMode.Equals("CBC"))
                {
                    if (encrypt)
                    {
                        blockCipherBuilder = cipherService.CreateBlockEncryptorBuilder(FipsTripleDes.Cbc.WithIV(ivValue));
                    }
                    else
                    {
                        blockCipherBuilder = cipherService.CreateBlockDecryptorBuilder(FipsTripleDes.Cbc.WithIV(ivValue));
                    }
                }
                else if (blockMode.Equals("CFB"))
                {
                    if (encrypt)
                    {
                        cipherBuilder = cipherService.CreateEncryptorBuilder(FipsTripleDes.Cfb64.WithIV(ivValue));
                    }
                    else
                    {
                        cipherBuilder = cipherService.CreateDecryptorBuilder(FipsTripleDes.Cfb64.WithIV(ivValue));
                    }
                }
                else if (blockMode.Equals("OFB"))
                {
                    if (encrypt)
                    {
                        cipherBuilder = cipherService.CreateEncryptorBuilder(FipsTripleDes.Ofb.WithIV(ivValue));
                    }
                    else
                    {
                        cipherBuilder = cipherService.CreateDecryptorBuilder(FipsTripleDes.Ofb.WithIV(ivValue));
                    }
                }
                else
                {
                    if (encrypt)
                    {
                        blockCipherBuilder = cipherService.CreateBlockEncryptorBuilder(FipsTripleDes.Ecb);
                    }
                    else
                    {
                        blockCipherBuilder = cipherService.CreateBlockDecryptorBuilder(FipsTripleDes.Ecb);
                    }
                }
            }
            else if (dekAlgName.StartsWith("DES-"))
            {
                sKey = getKey(password, 8, iv);
                throw new InvalidOperationException("no support for DES");
            }
            else if (dekAlgName.StartsWith("BF-"))
            {
                sKey = getKey(password, 16, iv);
                throw new InvalidOperationException("no support for Blowfish");
            }
            else if (dekAlgName.StartsWith("RC2-"))
            {
                int keyBits = 128;
                if (dekAlgName.StartsWith("RC2-40-"))
                {
                    keyBits = 40;
                }
                else if (dekAlgName.StartsWith("RC2-64-"))
                {
                    keyBits = 64;
                }
                //sKey = new RC2Parameters(getKey(password, keyBits / 8, iv).getKey(), keyBits);
                throw new InvalidOperationException("no support for RC2");
            }
            else if (dekAlgName.StartsWith("AES-"))
            {
                byte[] salt = iv;
                if (salt.Length > 8)
                {
                    salt = new byte[8];
                    Array.Copy(iv, 0, salt, 0, 8);
                }

                int keyBits;
                if (dekAlgName.StartsWith("AES-128-"))
                {
                    keyBits = 128;
                }
                else if (dekAlgName.StartsWith("AES-192-"))
                {
                    keyBits = 192;
                }
                else if (dekAlgName.StartsWith("AES-256-"))
                {
                    keyBits = 256;
                }
                else
                {
                    throw new InvalidOperationException("unknown AES encryption with private key: " + dekAlgName);
                }

                FipsAes.Key aesKey = new FipsAes.Key(getKey(password, keyBits / 8, salt));
                cipherService = CryptoServicesRegistrar.CreateService(aesKey);

                if (blockMode.Equals("CBC"))
                {
                    if (encrypt)
                    {
                        blockCipherBuilder = cipherService.CreateBlockEncryptorBuilder(FipsAes.Cbc.WithIV(ivValue));
                    }
                    else
                    {
                        blockCipherBuilder = cipherService.CreateBlockDecryptorBuilder(FipsAes.Cbc.WithIV(ivValue));
                    }
                }
                else if (blockMode.Equals("CFB"))
                {
                    if (encrypt)
                    {
                        cipherBuilder = cipherService.CreateEncryptorBuilder(FipsAes.Cfb128.WithIV(ivValue));
                    }
                    else
                    {
                        cipherBuilder = cipherService.CreateDecryptorBuilder(FipsAes.Cfb128.WithIV(ivValue));
                    }
                }
                else if (blockMode.Equals("OFB"))
                {
                    if (encrypt)
                    {
                        cipherBuilder = cipherService.CreateEncryptorBuilder(FipsAes.Ofb.WithIV(ivValue));
                    }
                    else
                    {
                        cipherBuilder = cipherService.CreateDecryptorBuilder(FipsAes.Ofb.WithIV(ivValue));
                    }
                }
                else
                {
                    if (encrypt)
                    {
                        blockCipherBuilder = cipherService.CreateBlockEncryptorBuilder(FipsAes.Ecb);
                    }
                    else
                    {
                        blockCipherBuilder = cipherService.CreateBlockDecryptorBuilder(FipsAes.Ecb);
                    }
                }
            }
            else
            {
                throw new InvalidOperationException("unknown encryption with private key: " + dekAlgName);
            }

            if (blockMode.Equals("CBC") || blockMode.Equals("ECB"))
            {
                if (encrypt)
                {
                    return(new PemBlockCipherImpl(encrypt, dekInfo, blockCipherBuilder));
                }
                else
                {
                    return(new PemBlockCipherImpl(encrypt, dekInfo, blockCipherBuilder));
                }
            }
            else
            {
                if (encrypt)
                {
                    return(new PemCipherImpl(dekInfo, cipherBuilder));
                }
                else
                {
                    return(new PemCipherImpl(dekInfo, cipherBuilder));
                }
            }
        }
 internal PemCipherImpl(DekInfo dekInfo, ICipherBuilder <IParameters <Algorithm> > baseCipher)
 {
     this.dekInfo    = dekInfo;
     this.baseCipher = baseCipher;
 }
 public RecipientOperator(ICipherBuilder <AlgorithmIdentifier> decryptor)
 {
     this.algorithmIdentifier = decryptor.AlgorithmDetails;
     this.op = decryptor;
 }
Exemple #16
0
 public MiscPemGenerator(Object o)
 {
     this.obj = o;
     this.encryptorBuilder = null;
 }
Exemple #17
0
 public MiscPemGenerator(Object o, ICipherBuilder <DekInfo> encryptorBuilder)
 {
     this.obj = o;
     this.encryptorBuilder = encryptorBuilder;
 }
 /**
  * generate an encrypted object that contains an Cms Encrypted Data structure.
  *
  * @param content the content to be encrypted
  * @param contentEncryptor the symmetric key based encryptor to encrypt the content with.
  */
 public CmsEncryptedData generate(
     ICmsTypedData content,
     ICipherBuilder <AlgorithmIdentifier> contentEncryptor)
 {
     return(doGenerate(content, contentEncryptor));
 }
 /// <summary>
 /// Add a SafeBag that is to be wrapped in a EncryptedData object.
 /// </summary>
 /// <param name="dataEncryptor">the encryptor to use for encoding the data.</param>
 /// <param name="data">the SafeBag to include.</param>
 /// <returns>this builder.</returns>
 public Pkcs12PfxPduBuilder AddEncryptedData(ICipherBuilder <AlgorithmIdentifier> dataEncryptor, Pkcs12SafeBag data)
 {
     return(addEncryptedData(dataEncryptor, new DerSequence(data.ToAsn1Structure())));
 }
Exemple #20
0
 public Pkcs12SafeBagBuilder(IAsymmetricPrivateKey privateKey, ICipherBuilder <AlgorithmIdentifier> encryptor) : this(PrivateKeyInfo.GetInstance(privateKey.GetEncoded()), encryptor)
 {
 }
Exemple #21
0
 internal PkixCipherBuilder(AlgorithmIdentifier algDetails, ICipherBuilder <IParameters <Algorithm> > baseCipherBuilder)
 {
     this.algDetails             = algDetails;
     this.baseBlockCipherBuilder = baseCipherBuilder;
 }
Exemple #22
0
 public Pkcs12SafeBagBuilder(PrivateKeyInfo privateKeyInfo, ICipherBuilder <AlgorithmIdentifier> encryptor)
 {
     this.bagType  = PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag;
     this.bagValue = new Pkcs8EncryptedPrivateKeyInfoBuilder(privateKeyInfo).Build(encryptor).ToAsn1Structure();
 }