private EncryptedValue EncryptData(byte[] data) { MemoryOutputStream bOut = new MemoryOutputStream(); Stream eOut = encryptor.BuildCipher(bOut).Stream; try { eOut.Write(data, 0, data.Length); BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(eOut); } catch (IOException e) { throw new CrmfException("cannot process data: " + e.Message, e); } AlgorithmIdentifier intendedAlg = null; AlgorithmIdentifier symmAlg = (AlgorithmIdentifier)encryptor.AlgorithmDetails; DerBitString encSymmKey; try { encSymmKey = new DerBitString(wrapper.Wrap(((KeyParameter)encryptor.Key).GetKey()).Collect()); } catch (Exception e) { throw new CrmfException("cannot wrap key: " + e.Message, e); } AlgorithmIdentifier keyAlg = (AlgorithmIdentifier)wrapper.AlgorithmDetails; Asn1OctetString valueHint = null; DerBitString encValue = new DerBitString(bOut.ToArray()); return(new EncryptedValue(intendedAlg, symmAlg, encSymmKey, keyAlg, valueHint, encValue)); }
public byte[] GetEncoded() { MemoryOutputStream bOut = new MemoryOutputStream(); this.Encode(bOut); return(bOut.ToArray()); }
private CmsEnvelopedData doGenerate( ICmsTypedData content, ICipherBuilderWithKey<AlgorithmIdentifier> contentEncryptor) { Asn1EncodableVector recipientInfos = new Asn1EncodableVector(); AlgorithmIdentifier encAlgId; Asn1OctetString encContent; MemoryOutputStream bOut = new MemoryOutputStream(); try { ICipher cOut = contentEncryptor.BuildCipher(bOut); content.Write(cOut.Stream); cOut.Stream.Close(); } catch (IOException e) { throw new CmsException(e.Message, e); } byte[] encryptedContent = bOut.ToArray(); encAlgId = contentEncryptor.AlgorithmDetails; encContent = new BerOctetString(encryptedContent); ISymmetricKey encKey = contentEncryptor.Key; for (IEnumerator<IRecipientInfoGenerator> it = recipientInfoGenerators.GetEnumerator(); it.MoveNext();) { IRecipientInfoGenerator recipient = (IRecipientInfoGenerator)it.Current; recipientInfos.Add(recipient.Generate(encKey)); } 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.EnvelopedData, new EnvelopedData(originatorInfo, new DerSet(recipientInfos), eci, unprotectedAttrSet)); return new CmsEnvelopedData(contentInfo); }
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())); }
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)); }
/// <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"); } }
private static SecretKeyPacket buildSecretKeyPacket(bool isMasterKey, PgpPrivateKey privKey, PgpPublicKey pubKey, IPbeSecretKeyEncryptor keyEncryptor) { BcpgObject secKey = (BcpgObject)privKey.Key; if (secKey == null) { if (isMasterKey) { return(new SecretKeyPacket(pubKey.publicPk, SymmetricKeyAlgorithmTag.Null, null, null, new byte[0])); } else { return(new SecretSubkeyPacket(pubKey.publicPk, SymmetricKeyAlgorithmTag.Null, null, null, new byte[0])); } } try { MemoryOutputStream bOut = new MemoryOutputStream(); BcpgOutputStream pOut = new BcpgOutputStream(bOut); pOut.WriteObject(secKey); byte[] keyData = bOut.ToArray(); byte[] checkData = checksum(keyEncryptor.ChecksumCalculatorFactory, keyData, keyData.Length); pOut.Write(checkData, 0, checkData.Length); PgpPbeKeyEncryptionParameters encParams = keyEncryptor.AlgorithmDetails; SymmetricKeyAlgorithmTag encAlgorithm = (keyEncryptor != null) ? encParams.Algorithm : SymmetricKeyAlgorithmTag.Null; if (encAlgorithm != SymmetricKeyAlgorithmTag.Null) { keyData = bOut.ToArray(); // include checksum byte[] encData = keyEncryptor.Wrap(keyData).Collect(); byte[] iv = encParams.GetIV(); S2k s2k = encParams.S2k; int s2kUsage; if (keyEncryptor.ChecksumCalculatorFactory != null) { if (keyEncryptor.ChecksumCalculatorFactory.AlgorithmDetails.Algorithm != HashAlgorithmTag.Sha1) { throw new PgpException("only SHA1 supported for key checksum calculations."); } s2kUsage = SecretKeyPacket.UsageSha1; } else { s2kUsage = SecretKeyPacket.UsageChecksum; } if (isMasterKey) { return(new SecretKeyPacket(pubKey.publicPk, encAlgorithm, s2kUsage, s2k, iv, encData)); } else { return(new SecretSubkeyPacket(pubKey.publicPk, encAlgorithm, s2kUsage, s2k, iv, encData)); } } else { if (isMasterKey) { return(new SecretKeyPacket(pubKey.publicPk, encAlgorithm, null, null, bOut.ToArray())); } else { return(new SecretSubkeyPacket(pubKey.publicPk, encAlgorithm, null, null, bOut.ToArray())); } } } catch (PgpException e) { throw e; } catch (Exception e) { throw new PgpException("Exception encrypting key", e); } }
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)); }