public IBlockResult Unwrap(byte[] cipherText, int offset, int length)
            {
                MemoryOutputStream mOut = new MemoryOutputStream();

                ICipher keyCipher = cipherBuilder.BuildCipher(mOut);

                keyCipher.Stream.Write(cipherText, offset, length);

                keyCipher.Stream.Close();

                return(new SimpleBlockResult(mOut.ToArray()));
            }
Ejemplo n.º 2
0
            public IBlockResult Wrap(byte[] keyData)
            {
                MemoryOutputStream mOut = new MemoryOutputStream();

                ICipher keyCipher = cipherBuilder.BuildCipher(mOut);

                keyCipher.Stream.Write(keyData, 0, keyData.Length);

                keyCipher.Stream.Close();

                return(new SimpleBlockResult(mOut.ToArray()));
            }
        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));
        }
Ejemplo n.º 4
0
        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");
            }
        }
Ejemplo n.º 8
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);
            }
        }
Ejemplo n.º 9
0
 public ICipher BuildCipher(Stream stream)
 {
     return(baseCipher.BuildCipher(stream));
 }
Ejemplo n.º 10
0
        private PemObject createPemObject(Object o)
        {
            String type;

            byte[] encoding;

            if (o is PemObject)
            {
                return((PemObject)o);
            }
            if (o is PemObjectGenerator)
            {
                return(((PemObjectGenerator)o).Generate());
            }
            if (o is X509Certificate)
            {
                type = "CERTIFICATE";

                encoding = ((X509Certificate)o).GetEncoded();
            }
            else if (o is X509Crl)
            {
                type = "X509 CRL";

                encoding = ((X509Crl)o).GetEncoded();
            }
            else if (o is X509TrustedCertificateBlock)
            {
                type = "TRUSTED CERTIFICATE";

                encoding = ((X509TrustedCertificateBlock)o).GetEncoded();
            }
            else if (o is PrivateKeyInfo)
            {
                PrivateKeyInfo      info   = (PrivateKeyInfo)o;
                DerObjectIdentifier algOID = info.PrivateKeyAlgorithm.Algorithm;

                if (algOID.Equals(PkcsObjectIdentifiers.RsaEncryption))
                {
                    type = "RSA PRIVATE KEY";

                    encoding = info.ParsePrivateKey().ToAsn1Object().GetEncoded();
                }
                else if (algOID.Equals(dsaOids[0]) || algOID.Equals(dsaOids[1]))
                {
                    type = "DSA PRIVATE KEY";

                    DsaParameter        p = DsaParameter.GetInstance(info.PrivateKeyAlgorithm.Parameters);
                    Asn1EncodableVector v = new Asn1EncodableVector();

                    v.Add(new DerInteger(0));
                    v.Add(new DerInteger(p.P));
                    v.Add(new DerInteger(p.Q));
                    v.Add(new DerInteger(p.G));

                    BigInteger x = DerInteger.GetInstance(info.ParsePrivateKey()).Value;
                    BigInteger y = p.G.ModPow(x, p.P);

                    v.Add(new DerInteger(y));
                    v.Add(new DerInteger(x));

                    encoding = new DerSequence(v).GetEncoded();
                }
                else if (algOID.Equals(X9ObjectIdentifiers.IdECPublicKey))
                {
                    type = "EC PRIVATE KEY";

                    encoding = info.ParsePrivateKey().ToAsn1Object().GetEncoded();
                }
                else
                {
                    type = "PRIVATE KEY";

                    encoding = info.GetEncoded();
                }
            }
            else if (o is SubjectPublicKeyInfo)
            {
                type = "PUBLIC KEY";

                encoding = ((SubjectPublicKeyInfo)o).GetEncoded();
            }

            /*
             * else if (o is X509AttributeCertificateHolder)
             * {
             *  type = "ATTRIBUTE CERTIFICATE";
             *  encoding = ((X509AttributeCertificateHolder)o).getEncoded();
             * }
             */
            else if (o is Pkcs8EncryptedPrivateKeyInfo)
            {
                type     = "ENCRYPTED PRIVATE KEY";
                encoding = ((Pkcs8EncryptedPrivateKeyInfo)o).GetEncoded();
            }
            else if (o is Pkcs10CertificationRequest)
            {
                type     = "CERTIFICATE REQUEST";
                encoding = ((Pkcs10CertificationRequest)o).GetEncoded();
            }
            else if (o is ContentInfo)
            {
                type     = "PKCS7";
                encoding = ((ContentInfo)o).GetEncoded();
            }
            else
            {
                throw new PemGenerationException("unknown object passed - can't encode.");
            }

            if (encryptorBuilder != null)
            {
                String dekAlgName = Platform.ToUpperInvariant(encryptorBuilder.AlgorithmDetails.Info);

                // Note: For backward compatibility
                if (dekAlgName.StartsWith("DESEDE"))
                {
                    dekAlgName = "DES-EDE3-CBC";
                }

                MemoryOutputStream bOut      = new MemoryOutputStream();
                ICipher            encryptor = encryptorBuilder.BuildCipher(bOut);

                using (var stream = encryptor.Stream)
                {
                    stream.Write(encoding, 0, encoding.Length);
                }

                byte[] encData = bOut.ToArray();

                IList headers = Platform.CreateArrayList();

                headers.Add(new PemHeader("Proc-Type", "4,ENCRYPTED"));
                headers.Add(new PemHeader("DEK-Info", encryptorBuilder.AlgorithmDetails.Info));

                return(new PemObject(type, headers, encData));
            }

            return(new PemObject(type, encoding));
        }