public static Stream Decrypt(Stream inputStream, PgpPrivateKey privateKey) { using Stream decoderStream = PgpUtilities.GetDecoderStream(inputStream); PgpObjectFactory decoderFactory = new(decoderStream); PgpEncryptedDataList dataList = decoderFactory.NextPgpObject() as PgpEncryptedDataList ?? (PgpEncryptedDataList)decoderFactory.NextPgpObject(); PgpPublicKeyEncryptedData data = dataList.GetEncryptedDataObjects().Cast <PgpPublicKeyEncryptedData>().First(); using Stream dataStream = data.GetDataStream(privateKey); PgpObjectFactory dataFactory = new(dataStream); if (dataFactory.NextPgpObject() is not PgpCompressedData compressedData) { throw new Exception(); } using Stream compressedStream = compressedData.GetDataStream(); PgpObjectFactory factory = new(compressedStream); PgpLiteralData literal = factory.NextPgpObject() as PgpLiteralData ?? (PgpLiteralData)factory.NextPgpObject(); MemoryStream output = new(); using (Stream input = literal.GetInputStream()) { Streams.PipeAll(input, output); } output.Seek(0L, SeekOrigin.Begin); return(output); }
public String DecryptKeycode(String privateKeyStr, String encryptedKeycode) { byte[] rawMessage = System.Text.Encoding.ASCII.GetBytes(encryptedKeycode); Stream inputStream = new MemoryStream(rawMessage); inputStream = PgpUtilities.GetDecoderStream(inputStream); PgpObjectFactory pgpF = new PgpObjectFactory(inputStream); PgpEncryptedDataList enc = null; PgpObject o = pgpF.NextPgpObject(); // // the first object might be a PGP marker packet. // if (o is PgpEncryptedDataList) { enc = (PgpEncryptedDataList)o; } else { enc = (PgpEncryptedDataList)pgpF.NextPgpObject(); } byte[] decodedPrivateKey = System.Text.Encoding.ASCII.GetBytes(privateKeyStr); PgpPrivateKey key = null; Stream decodedStream = PgpUtilities.GetDecoderStream(new MemoryStream(decodedPrivateKey)); PgpSecretKeyRingBundle privRings = new PgpSecretKeyRingBundle(decodedStream); PgpPublicKeyEncryptedData dataObject = null; foreach (PgpPublicKeyEncryptedData encryptedData in enc.GetEncryptedDataObjects()) { key = FindKeyById(privRings, encryptedData.KeyId); dataObject = encryptedData; } if (key == null) { throw new SendSafely.Exceptions.InvalidKeyException("Can't find encryption key in key ring."); } Stream dataStream = dataObject.GetDataStream(key); PgpObjectFactory pgpFact = new PgpObjectFactory(dataStream); PgpLiteralData ld = (PgpLiteralData)pgpFact.NextPgpObject(); Stream unc = ld.GetInputStream(); String keycode; using (StreamReader reader = new StreamReader(unc, Encoding.UTF8)) { keycode = reader.ReadToEnd(); } return(keycode); }
private static PgpPublicKeyEncryptedData extractPublicKey(PgpEncryptedDataList encryptedDataList) { PgpPublicKeyEncryptedData publicKeyED = null; foreach (PgpPublicKeyEncryptedData privateKeyED in encryptedDataList.GetEncryptedDataObjects()) { if (privateKeyED != null) { publicKeyED = privateKeyED; break; } } return(publicKeyED); }
// Note: I was able to extract the private key into xml format .Net expecs with this public static string GetPrivateKeyXml(string inputData) { Stream inputStream = IoHelper.GetStream(inputData); PgpObjectFactory pgpFactory = new PgpObjectFactory(PgpUtilities.GetDecoderStream(inputStream)); PgpObject pgp = null; if (pgpFactory != null) { pgp = pgpFactory.NextPgpObject(); } PgpEncryptedDataList encryptedData = null; if (pgp is PgpEncryptedDataList) { encryptedData = (PgpEncryptedDataList)pgp; } else { encryptedData = (PgpEncryptedDataList)pgpFactory.NextPgpObject(); } Stream privateKeyStream = File.OpenRead(PrivateKeyOnlyPath); // find secret key PgpSecretKeyRingBundle pgpKeyRing = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(privateKeyStream)); PgpPrivateKey privateKey = null; foreach (PgpPublicKeyEncryptedData pked in encryptedData.GetEncryptedDataObjects()) { privateKey = FindSecretKey(pgpKeyRing, pked.KeyId, Password.ToCharArray()); if (privateKey != null) { //pubKeyData = pked; break; } } // get xml: RsaPrivateCrtKeyParameters rpckp = ((RsaPrivateCrtKeyParameters)privateKey.Key); RSAParameters dotNetParams = DotNetUtilities.ToRSAParameters(rpckp); RSA rsa = RSA.Create(); rsa.ImportParameters(dotNetParams); string xmlPrivate = rsa.ToXmlString(true); return(xmlPrivate); }
private static PgpObjectFactory RetrievePgpObjectFactory(PgpEncryptedDataList dataList, PgpSecretKeyRingBundle secretKeyRing, string passPhrase) { PgpPublicKeyEncryptedData publicKeyEncryptedData = dataList.GetEncryptedDataObjects().Cast <PgpPublicKeyEncryptedData>() .FirstOrDefault(dd => FindSecretKeyByKeyId(secretKeyRing, dd.KeyId, passPhrase.ToCharArray()) != null); if (publicKeyEncryptedData == null) { throw new ArgumentException("Secret key for message not found."); } PgpPrivateKey privateKey = FindSecretKeyByKeyId(secretKeyRing, publicKeyEncryptedData.KeyId, passPhrase.ToCharArray()); using (Stream stream = publicKeyEncryptedData.GetDataStream(privateKey)) { return(new PgpObjectFactory(stream)); } }
private static Tuple <PgpPublicKeyEncryptedData, PgpObjectFactory> Decrypt(PgpEncryptedDataList pgpEncryptedDatalist, Stream privateKeyStream, string praKeyPwd) { var pkstream = Org.BouncyCastle.Bcpg.OpenPgp.PgpUtilities.GetDecoderStream(privateKeyStream); var bundle = new Org.BouncyCastle.Bcpg.OpenPgp.PgpSecretKeyRingBundle(pkstream); foreach (PgpPublicKeyEncryptedData encryptedData in pgpEncryptedDatalist.GetEncryptedDataObjects()) { var privateKey = bundle.GetSecretKey(encryptedData.KeyId)?.ExtractPrivateKey(praKeyPwd.ToCharArray()); if (privateKey == null) { continue; } using (var tmp = encryptedData.GetDataStream(privateKey)) { return(Tuple.Create(encryptedData, new PgpObjectFactory(tmp))); } } throw new ArgumentException("未能正常读取到加密文件内容,请检查文件及密钥"); }
/* * PGP decrypt a given stream. */ public void Decrypt(Stream inputStream, Stream outputStream, Stream privateKeyStream, string passPhrase) { if (inputStream == null) { throw new ArgumentException(nameof(inputStream)); } if (outputStream == null) { throw new ArgumentException(nameof(outputStream)); } if (privateKeyStream == null) { throw new ArgumentException(nameof(privateKeyStream)); } if (passPhrase == null) { passPhrase = String.Empty; } PgpObjectFactory objFactory = new PgpObjectFactory(PgpUtilities.GetDecoderStream(inputStream)); // find secret key PgpSecretKeyRingBundle pgpSec = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(privateKeyStream)); PgpObject obj = null; if (objFactory != null) { obj = objFactory.NextPgpObject(); } // the first object might be a PGP marker packet. PgpEncryptedDataList enc = null; if (obj is PgpEncryptedDataList) { enc = (PgpEncryptedDataList)obj; } else { enc = (PgpEncryptedDataList)objFactory.NextPgpObject(); } // decrypt PgpPrivateKey privateKey = null; PgpPublicKeyEncryptedData pbe = null; foreach (PgpPublicKeyEncryptedData pked in enc.GetEncryptedDataObjects()) { privateKey = FindSecretKey(pgpSec, pked.KeyId, passPhrase.ToCharArray()); if (privateKey != null) { pbe = pked; break; } } if (privateKey == null) { throw new ArgumentException("Secret key for message not found."); } PgpObjectFactory plainFact = null; using (Stream clear = pbe.GetDataStream(privateKey)) { plainFact = new PgpObjectFactory(clear); } PgpObject message = plainFact.NextPgpObject(); if (message is PgpOnePassSignatureList) { message = plainFact.NextPgpObject(); } if (message is PgpCompressedData) { PgpCompressedData cData = (PgpCompressedData)message; PgpObjectFactory of = null; using (Stream compDataIn = cData.GetDataStream()) { of = new PgpObjectFactory(compDataIn); } message = of.NextPgpObject(); if (message is PgpOnePassSignatureList) { message = of.NextPgpObject(); PgpLiteralData Ld = null; Ld = (PgpLiteralData)message; Stream unc = Ld.GetInputStream(); Streams.PipeAll(unc, outputStream); } else { PgpLiteralData Ld = null; Ld = (PgpLiteralData)message; Stream unc = Ld.GetInputStream(); Streams.PipeAll(unc, outputStream); } } else if (message is PgpLiteralData) { PgpLiteralData ld = (PgpLiteralData)message; string outFileName = ld.FileName; Stream unc = ld.GetInputStream(); Streams.PipeAll(unc, outputStream); } else if (message is PgpOnePassSignatureList) { throw new PgpException("Encrypted message contains a signed message - not literal data."); } else { throw new PgpException("Message is not a simple encrypted file."); } }
/// <summary> /// Initializes a new instance of the <see cref="PgpFileDecryptingStream"/> class. /// </summary> /// <param name="inputStream">The encrypted input stream.</param> /// <param name="secretKeyRingBundle">The secret key ring bundle.</param> /// <param name="passPhrase">The pass phrase.</param> /// <exception cref="System.ArgumentException">Secret key for message not found.</exception> /// <exception cref="PgpException"> /// Encrypted message contains a signed message - not literal data. /// or /// Message is not a simple encrypted file - type unknown. /// </exception> public PgpFileDecryptingStream( Stream inputStream, PgpSecretKeyRingBundle secretKeyRingBundle, string passPhrase) { inputStream = PgpUtilities.GetDecoderStream(inputStream); PgpObjectFactory encryptedObjectFactory = new PgpObjectFactory(inputStream); // the first object might be a PGP marker packet. PgpEncryptedDataList encryptedList = encryptedObjectFactory.NextPgpObject() as PgpEncryptedDataList; if (encryptedList == null) { encryptedList = (PgpEncryptedDataList)encryptedObjectFactory.NextPgpObject(); } // decrypt PgpPrivateKey privateKey = null; PgpPublicKeyEncryptedData encryptedData = null; foreach (PgpPublicKeyEncryptedData pked in encryptedList.GetEncryptedDataObjects()) { privateKey = PgpHelper.FindSecretKey(secretKeyRingBundle, pked.KeyId, passPhrase.ToCharArray()); if (privateKey != null) { encryptedData = pked; break; } } if (privateKey == null) { throw new ArgumentException("Secret key for message not found."); } PgpObjectFactory decryptedObjectFactory = null; using (Stream decryptedStream = encryptedData.GetDataStream(privateKey)) { decryptedObjectFactory = new PgpObjectFactory(decryptedStream); } PgpObject message = decryptedObjectFactory.NextPgpObject(); if (message is PgpCompressedData) { PgpCompressedData compressedData = (PgpCompressedData)message; PgpObjectFactory decompressedObjectFactory = null; using (Stream decompressedStream = compressedData.GetDataStream()) { decompressedObjectFactory = new PgpObjectFactory(decompressedStream); } message = decompressedObjectFactory.NextPgpObject(); if (message is PgpOnePassSignatureList) { message = decompressedObjectFactory.NextPgpObject(); } } if (message is PgpOnePassSignatureList) { throw new PgpException("Encrypted message contains a signed message - not literal data."); } else if (!(message is PgpLiteralData)) { throw new PgpException("Message is not a simple encrypted file - type unknown."); } PgpLiteralData ld = (PgpLiteralData)message; this.WrappedFileName = ld.FileName; this.WrappedFileModifiedTime = ld.ModificationTime; this.wrappedStream = ld.GetInputStream(); }
private static bool DecryptPgpData(Stream inputStream, Stream outputstream, Stream privateKeyStream, string passPhrase) { bool success = false; PgpObjectFactory pgpFactory = new PgpObjectFactory(PgpUtilities.GetDecoderStream(inputStream)); // find secret key PgpSecretKeyRingBundle pgpKeyRing = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(privateKeyStream)); PgpObject pgp = null; if (pgpFactory != null) { pgp = pgpFactory.NextPgpObject(); } // the first object might be a PGP marker packet. PgpEncryptedDataList encryptedData = null; if (pgp is PgpEncryptedDataList) { encryptedData = (PgpEncryptedDataList)pgp; } else { encryptedData = (PgpEncryptedDataList)pgpFactory.NextPgpObject(); } // decrypt PgpPrivateKey privateKey = null; PgpPublicKeyEncryptedData pubKeyData = null; foreach (PgpPublicKeyEncryptedData pubKeyDataItem in encryptedData.GetEncryptedDataObjects()) { privateKey = FindSecretKey(pgpKeyRing, pubKeyDataItem.KeyId, passPhrase.ToCharArray()); if (privateKey != null) { pubKeyData = pubKeyDataItem; break; } } if (privateKey == null) { throw new ArgumentException("Secret key for message not found."); } PgpObjectFactory plainFact = null; using (Stream clear = pubKeyData.GetDataStream(privateKey)) { plainFact = new PgpObjectFactory(clear); } PgpObject message = plainFact.NextPgpObject(); if (message is PgpCompressedData) { PgpCompressedData compressedData = (PgpCompressedData)message; PgpObjectFactory pgpCompressedFactory = null; using (Stream compDataIn = compressedData.GetDataStream()) { pgpCompressedFactory = new PgpObjectFactory(compDataIn); } message = pgpCompressedFactory.NextPgpObject(); PgpLiteralData literalData = null; if (message is PgpOnePassSignatureList) { message = pgpCompressedFactory.NextPgpObject(); } literalData = (PgpLiteralData)message; using (Stream unc = literalData.GetInputStream()) { byte[] b = null; IOHelper.PutbyteDataInStream(unc, ref b); IOHelper.WriteStream(outputstream, ref b); success = true; } } else if (message is PgpLiteralData) { PgpLiteralData literalData = (PgpLiteralData)message; using (Stream unc = literalData.GetInputStream()) { byte[] b = null; IOHelper.PutbyteDataInStream(unc, ref b); IOHelper.PutbyteDataInStream(outputstream, ref b); success = true; } } else if (message is PgpOnePassSignatureList) { throw new PgpException("Encrypted message contains a signed message - not literal data."); } else { throw new PgpException("Message is not a simple encrypted file - type unknown."); } return(success); }
/// <summary> /// Attempt to decrypt a PGP protected message using the matching private key. /// </summary> /// <param name="messageStream">Stream containing the message to decrypt.</param> /// <param name="decryptedMessageStream">Stream to write the decrypted message into.</param> /// <param name="recipientPrivateKey">The BouncyCastle private key to be used for decryption.</param> /// <remarks>The message should be passed in without ASCII Armor.</remarks> /// <returns>Whether the decryption completed successfully.</returns> public static bool Decrypt(Stream messageStream, Stream decryptedMessageStream, PgpPrivateKey recipientPrivateKey) { // Decode from Base-64. using (Stream decoderStream = PgpUtilities.GetDecoderStream(messageStream)) { // Extract the encrypted data list. PgpObjectFactory pgpObjectFactory = new PgpObjectFactory(decoderStream); PgpObject pgpObject = pgpObjectFactory.NextPgpObject(); while (!(pgpObject is PgpEncryptedDataList)) { pgpObject = pgpObjectFactory.NextPgpObject(); if (pgpObject == null) { return(false); } } PgpEncryptedDataList pgpEncryptedDataList = pgpObject as PgpEncryptedDataList; // Attempt to extract the encrypted data stream. Stream decryptedStream = null; foreach (PgpPublicKeyEncryptedData pgpEncryptedData in pgpEncryptedDataList.GetEncryptedDataObjects().Cast <PgpPublicKeyEncryptedData>()) { if (pgpEncryptedData.KeyId == recipientPrivateKey.KeyId) { decryptedStream = pgpEncryptedData.GetDataStream(recipientPrivateKey); } } // If we're unable to decrypt any of the streams, fail. if (decryptedStream == null) { return(false); } PgpObjectFactory clearPgpObjectFactory = new PgpObjectFactory(decryptedStream); PgpObject message = clearPgpObjectFactory.NextPgpObject(); // Deal with compression. if (message is PgpCompressedData) { PgpCompressedData compressedMessage = (PgpCompressedData)message; using (Stream compressedDataStream = compressedMessage.GetDataStream()) { PgpObjectFactory compressedPgpObjectFactory = new PgpObjectFactory(compressedDataStream); pgpObject = compressedPgpObjectFactory.NextPgpObject(); while (!(pgpObject is PgpLiteralData)) { pgpObject = compressedPgpObjectFactory.NextPgpObject(); if (pgpObject == null) { return(false); } } } } else if (message is PgpLiteralData) { pgpObject = message; } else { // If not compressed and the following object isn't literal data, fail. decryptedStream.Dispose(); return(false); } // If a literal data stream was found, extract the decrypted message. PgpLiteralData literalData = pgpObject as PgpLiteralData; if (literalData != null) { using (Stream literalDataStream = literalData.GetDataStream()) { literalDataStream.CopyTo(decryptedMessageStream); } decryptedStream.Dispose(); return(true); } } return(false); }
public String DecryptAndVerifySignature(byte[] encryptData, Stream decryptData) { try { var bais = PgpUtilities.GetDecoderStream(new MemoryStream(encryptData)); PgpObjectFactory objectFactory = new PgpObjectFactory(bais); var firstObject = objectFactory.NextPgpObject(); PgpEncryptedDataList dataList = (PgpEncryptedDataList)(firstObject is PgpEncryptedDataList ? firstObject : objectFactory.NextPgpObject()); PgpPrivateKey privateKey = null; PgpPublicKeyEncryptedData encryptedData = null; var list = dataList.GetEncryptedDataObjects(); foreach (var obj in list) { if (privateKey != null) { break; } encryptedData = (PgpPublicKeyEncryptedData)obj; privateKey = FindSecretKey(encryptedData.KeyId); } if (privateKey == null || encryptedData == null) { throw new ArgumentException("secret key for message not found."); } Stream clear = encryptedData.GetDataStream(privateKey); PgpObjectFactory clearObjectFactory = new PgpObjectFactory(clear); var message = clearObjectFactory.NextPgpObject(); if (message is PgpCompressedData) { PgpCompressedData cData = (PgpCompressedData)message; objectFactory = new PgpObjectFactory(cData.GetDataStream()); message = objectFactory.NextPgpObject(); } PgpOnePassSignature calculatedSignature = null; if (message is PgpOnePassSignatureList) { calculatedSignature = ((PgpOnePassSignatureList)message)[0]; calculatedSignature.InitVerify(publicKey); message = objectFactory.NextPgpObject(); } var baos = new MemoryStream(); if (message is PgpLiteralData) { PgpLiteralData ld = (PgpLiteralData)message; Stream unc = ld.GetInputStream(); int ch; while ((ch = unc.ReadByte()) >= 0) { if (calculatedSignature != null) { calculatedSignature.Update((byte)ch); } baos.WriteByte((byte)ch); } } else if (message is PgpOnePassSignatureList) { throw new PgpException("encrypted message contains a signed message - not literal data."); } else { throw new PgpException("message is not a simple encrypted file - type unknown."); } return(Encoding.UTF8.GetString(baos.ToArray())); } catch (Exception e) { Console.WriteLine(e); throw; } }
/// <summary> /// Decrypt file /// </summary> /// <param name="inputStream">Encrypted file</param> /// <param name="privateKeyStream">Private key</param> /// <param name="passPhrase">Passphrase</param> /// <returns></returns> public PgpLiteralData Decrypt(Stream inputStream, Stream privateKeyStream, string passPhrase) { try { PgpObject pgpObj = null; var pgpObjFactory = new PgpObjectFactory(PgpUtilities.GetDecoderStream(inputStream)); var pgpScrKey = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(privateKeyStream)); if (pgpObjFactory != null) { pgpObj = pgpObjFactory.NextPgpObject(); } PgpEncryptedDataList pgpEncrDataList = null; // the first object might be a PGP marker packet. if (pgpObj is PgpEncryptedDataList) { pgpEncrDataList = (PgpEncryptedDataList)pgpObj; } else { pgpEncrDataList = (PgpEncryptedDataList)pgpObjFactory.NextPgpObject(); } PgpPrivateKey pgpPrvtKey = null; PgpPublicKeyEncryptedData pgpPblcKeyEncrData = null; // decrypt foreach (PgpPublicKeyEncryptedData pked in pgpEncrDataList.GetEncryptedDataObjects()) { pgpPrvtKey = FindSecretKey(pgpScrKey, pked.KeyId, passPhrase.ToCharArray()); if (pgpPrvtKey != null) { pgpPblcKeyEncrData = pked; break; } } if (pgpPrvtKey == null) { throw new ArgumentException("Secret key for file not found."); } using (Stream clear = pgpPblcKeyEncrData.GetDataStream(pgpPrvtKey)) { var plainFact = new PgpObjectFactory(clear); PgpObject pgpFile = plainFact.NextPgpObject(); if (pgpFile is PgpCompressedData cData) { using (Stream compDataIn = cData.GetDataStream()) { var of = new PgpObjectFactory(compDataIn); pgpFile = of.NextPgpObject(); if (pgpFile is PgpOnePassSignatureList) { pgpFile = of.NextPgpObject(); return((PgpLiteralData)pgpFile); } else { return((PgpLiteralData)pgpFile); } } } else if (pgpFile is PgpLiteralData) { return((PgpLiteralData)pgpFile); } else if (pgpFile is PgpOnePassSignatureList) { throw new PgpException("Encrypted file contains a signed data - not literal data."); } else { throw new PgpException("File is not a simple encrypted file - type unknown."); } } } catch (PgpException ex) { //TODO: Add log throw ex; } }
public static string Decrypt( Stream inputStream, string privateKeyIn, string passPhrase, out Stream outputStream) { PgpObjectFactory objFactory = new PgpObjectFactory(PgpUtilities.GetDecoderStream(inputStream)); outputStream = new MemoryStream(); PgpObject obj = null; if (objFactory != null) { obj = objFactory.NextPgpObject(); } // the first object might be a PGP marker packet. PgpEncryptedDataList enc = null; PgpObject message = null; if (obj is PgpEncryptedDataList) { enc = (PgpEncryptedDataList)obj; } else if (obj is PgpCompressedData) { message = (PgpCompressedData)obj; } else { enc = (PgpEncryptedDataList)objFactory.NextPgpObject(); } // If enc and message are null at this point, we failed to detect the contents of the encrypted stream. if (enc == null && message == null) { throw new ArgumentException($"Failed to detect encrypted content format."); } // decrypt PgpPrivateKey privateKey = null; PgpPublicKeyEncryptedData pbe = null; PgpSecretKeyRingBundle pgpSecret = null; byte[] privateKeyBuffer = Encoding.ASCII.GetBytes(privateKeyIn); MemoryStream privateKeyStream = new MemoryStream(privateKeyBuffer); pgpSecret = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(privateKeyStream)); if (enc != null) { foreach (PgpPublicKeyEncryptedData pked in enc.GetEncryptedDataObjects()) { privateKey = FindSecretKey(pgpSecret, pked.KeyId, passPhrase.ToCharArray()); if (privateKey != null) { pbe = pked; break; } } if (privateKey == null) { throw new ArgumentException($"Secret key for message not found."); } PgpObjectFactory plainFact = null; using (Stream clear = pbe.GetDataStream(privateKey)) { plainFact = new PgpObjectFactory(clear); } message = plainFact.NextPgpObject(); if (message is PgpOnePassSignatureList) { message = plainFact.NextPgpObject(); } } if (message is PgpCompressedData) { PgpCompressedData cData = (PgpCompressedData)message; PgpObjectFactory of = null; using (Stream compDataIn = cData.GetDataStream()) { of = new PgpObjectFactory(compDataIn); } message = of.NextPgpObject(); if (message is PgpOnePassSignatureList) { message = of.NextPgpObject(); PgpLiteralData Ld = null; Ld = (PgpLiteralData)message; Stream unc = Ld.GetInputStream(); Streams.PipeAll(unc, outputStream); } else { PgpLiteralData Ld = null; Ld = (PgpLiteralData)message; Stream unc = Ld.GetInputStream(); Streams.PipeAll(unc, outputStream); } } else if (message is PgpLiteralData) { PgpLiteralData ld = (PgpLiteralData)message; string outFileName = ld.FileName; Stream unc = ld.GetInputStream(); Streams.PipeAll(unc, outputStream); if (pbe.IsIntegrityProtected()) { if (!pbe.Verify()) { throw new PgpException($"Message failed integrity check."); } } } else if (message is PgpOnePassSignatureList) { throw new PgpException($"Encrypted message contains a signed message - not literal data."); } else { throw new PgpException($"Message is not a simple encrypted file."); } byte[] outputBuffer = (outputStream as MemoryStream).ToArray(); return(Encoding.ASCII.GetString(outputBuffer)); }
/// <summary> /// Decrypt file /// </summary> /// <param name="inputStream">Input file stream</param> /// <param name="privateKey">Private key stream</param> /// <param name="outputFile">Output file name</param> /// <param name="password">PGP key password</param> private static void DecryptFile(Stream inputStream, Stream privateKey, string outputFile, char[] password) { inputStream = PgpUtilities.GetDecoderStream(inputStream); PgpObjectFactory pgpFactory = new PgpObjectFactory(inputStream); PgpEncryptedDataList encryptedData = null; PgpObject pgpObj = pgpFactory.NextPgpObject(); // The first object might be a PGP marker packet. if (pgpObj is PgpEncryptedDataList) { encryptedData = (PgpEncryptedDataList)pgpObj; } else { encryptedData = (PgpEncryptedDataList)pgpFactory.NextPgpObject(); } // Find the secret key PgpPrivateKey sKey = null; PgpPublicKeyEncryptedData pbe = null; PgpSecretKeyRingBundle pgpSec = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(privateKey)); foreach (PgpPublicKeyEncryptedData pked in encryptedData.GetEncryptedDataObjects()) { sKey = FindSecretKey(pgpSec, pked.KeyId, password); if (sKey != null) { pbe = pked; break; } } if (sKey == null) { throw new ArgumentException("Secret key for message not found."); } Stream clear = pbe.GetDataStream(sKey); PgpObjectFactory plainFact = new PgpObjectFactory(clear); PgpObject message = plainFact.NextPgpObject(); if (message is PgpCompressedData) { PgpCompressedData cData = (PgpCompressedData)message; PgpObjectFactory pgpFact = new PgpObjectFactory(cData.GetDataStream()); message = pgpFact.NextPgpObject(); } // Write decrypted file to disk if (message is PgpLiteralData) { PgpLiteralData ld = (PgpLiteralData)message; Stream fOut = File.Create(outputFile); Stream unc = ld.GetInputStream(); Streams.PipeAll(unc, fOut); fOut.Close(); } else if (message is PgpOnePassSignatureList) { throw new PgpException("Encrypted message contains a signed message - not literal data."); } else { throw new PgpException("Message is not a simple encrypted file - type unknown."); } }
public static Stream PgpDecrypt( Stream encryptedData, string armoredPrivateKey, string privateKeyPassword, Encoding armorEncoding = null) { armorEncoding = armorEncoding ?? Encoding.UTF8; var stream = PgpUtilities.GetDecoderStream(encryptedData); var layeredStreams = new List <Stream> { stream }; //this is to clean up/ dispose of any layered streams. var dataObjectFactory = new PgpObjectFactory(stream); var dataObject = dataObjectFactory.NextPgpObject(); Dictionary <long, PgpSecretKey> secretKeys; using (var privateKeyStream = armoredPrivateKey.Streamify(armorEncoding)) { var secRings = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(privateKeyStream)).GetKeyRings() .OfType <PgpSecretKeyRing>(); var pgpSecretKeyRings = secRings as PgpSecretKeyRing[] ?? secRings.ToArray(); if (!pgpSecretKeyRings.Any()) { throw new ArgumentException("No secret keys found."); } secretKeys = pgpSecretKeyRings.SelectMany(x => x.GetSecretKeys().OfType <PgpSecretKey>()) .ToDictionary(key => key.KeyId, value => value); } while (!(dataObject is PgpLiteralData) && dataObject != null) { try { PgpCompressedData compressedData = null; PgpEncryptedDataList listedData = null; if (dataObject as PgpCompressedData != null) { compressedData = dataObject as PgpCompressedData; } if (dataObject as PgpEncryptedDataList != null) { listedData = dataObject as PgpEncryptedDataList; } if (compressedData == null && listedData == null) { return(null); } //strip away the compression stream if (compressedData != null) { stream = compressedData.GetDataStream(); layeredStreams.Add(stream); dataObjectFactory = new PgpObjectFactory(stream); } //strip the PgpEncryptedDataList if (listedData != null) { var encryptedDataList = listedData.GetEncryptedDataObjects().OfType <PgpPublicKeyEncryptedData>().First(); var decryptionKey = secretKeys[encryptedDataList.KeyId].ExtractPrivateKey(privateKeyPassword.ToCharArray()); stream = encryptedDataList.GetDataStream(decryptionKey); layeredStreams.Add(stream); dataObjectFactory = new PgpObjectFactory(stream); } dataObject = dataObjectFactory.NextPgpObject(); } catch (Exception ex) { throw new PgpException("Failed to strip encapsulating streams.", ex); } } foreach (var layeredStream in layeredStreams) { layeredStream.Close(); layeredStream.Dispose(); } if (dataObject == null) { return(null); } var literalData = (PgpLiteralData)dataObject; var ms = new MemoryStream(); using (var clearData = literalData.GetInputStream()) { Streams.PipeAll(clearData, ms); } ms.Position = 0; return(ms); }
/* * PGP decrypt and verify a given stream. */ private void DecryptAndVerify(Stream inputStream, Stream outputStream, Stream publicKeyStream, Stream privateKeyStream, string passPhrase) { EncryptionKeys encryptionKeys = new EncryptionKeys(publicKeyStream, privateKeyStream, passPhrase); PgpPublicKeyEncryptedData publicKeyED = Utilities.ExtractPublicKeyEncryptedData(inputStream); if (publicKeyED.KeyId != encryptionKeys.PublicKey.KeyId) { throw new PgpException(String.Format("Failed to verify file.")); } PgpObject message = Utilities.GetClearCompressedMessage(publicKeyED, encryptionKeys); PgpObjectFactory objFactory = new PgpObjectFactory(PgpUtilities.GetDecoderStream(inputStream)); // find secret key PgpSecretKeyRingBundle pgpSec = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(privateKeyStream)); PgpObject obj = null; if (objFactory != null) { obj = objFactory.NextPgpObject(); } // the first object might be a PGP marker packet. PgpEncryptedDataList enc = null; if (obj is PgpEncryptedDataList) { enc = (PgpEncryptedDataList)obj; } else { enc = (PgpEncryptedDataList)objFactory.NextPgpObject(); } // decrypt PgpPrivateKey privateKey = null; PgpPublicKeyEncryptedData pbe = null; foreach (PgpPublicKeyEncryptedData pked in enc.GetEncryptedDataObjects()) { privateKey = FindSecretKey(pgpSec, pked.KeyId, passPhrase.ToCharArray()); if (privateKey != null) { pbe = pked; break; } } if (privateKey == null) { throw new ArgumentException("Secret key for message not found."); } PgpObjectFactory plainFact = null; using (Stream clear = pbe.GetDataStream(privateKey)) { plainFact = new PgpObjectFactory(clear); } if (message is PgpCompressedData) { PgpCompressedData cData = (PgpCompressedData)message; PgpObjectFactory of = null; using (Stream compDataIn = cData.GetDataStream()) { of = new PgpObjectFactory(compDataIn); } message = of.NextPgpObject(); if (message is PgpOnePassSignatureList) { message = of.NextPgpObject(); PgpLiteralData Ld = null; Ld = (PgpLiteralData)message; Stream unc = Ld.GetInputStream(); Streams.PipeAll(unc, outputStream); } else { PgpLiteralData Ld = null; Ld = (PgpLiteralData)message; Stream unc = Ld.GetInputStream(); Streams.PipeAll(unc, outputStream); } } else if (message is PgpLiteralData) { PgpLiteralData ld = (PgpLiteralData)message; string outFileName = ld.FileName; Stream unc = ld.GetInputStream(); Streams.PipeAll(unc, outputStream); if (pbe.IsIntegrityProtected()) { if (!pbe.Verify()) { throw new PgpException("Message failed integrity check."); } } } else { throw new PgpException("Message is not a simple encrypted file."); } }
private static void Decrypt(Stream inputStream, Stream privateKeyStream, string passPhrase, string outputFile) { try { PgpObjectFactory pgpF = null; PgpEncryptedDataList enc = null; PgpObject o = null; PgpPrivateKey sKey = null; PgpPublicKeyEncryptedData pbe = null; PgpSecretKeyRingBundle pgpSec = null; pgpF = new PgpObjectFactory(PgpUtilities.GetDecoderStream(inputStream)); pgpSec = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(privateKeyStream)); if (pgpF != null) { o = pgpF.NextPgpObject(); } if (o is PgpEncryptedDataList) { enc = (PgpEncryptedDataList)o; } else { enc = (PgpEncryptedDataList)pgpF.NextPgpObject(); } foreach (PgpPublicKeyEncryptedData pked in enc.GetEncryptedDataObjects()) { sKey = FindSecretKey(pgpSec, pked.KeyId, passPhrase.ToCharArray()); if (sKey != null) { pbe = pked; break; } } if (sKey == null) { throw new ArgumentException("Secret key for message not found."); } PgpObjectFactory plainFact = null; using (Stream clear = pbe.GetDataStream(sKey)) { plainFact = new PgpObjectFactory(clear); } PgpObject message = plainFact.NextPgpObject(); if (message is PgpCompressedData) { PgpCompressedData cData = (PgpCompressedData)message; PgpObjectFactory of = null; using (Stream compDataIn = cData.GetDataStream()) { of = new PgpObjectFactory(compDataIn); } message = of.NextPgpObject(); if (message is PgpOnePassSignatureList) { message = of.NextPgpObject(); PgpLiteralData Ld = null; Ld = (PgpLiteralData)message; using (Stream output = File.Create(outputFile)) { Stream unc = Ld.GetInputStream(); Streams.PipeAll(unc, output); } } else { PgpLiteralData Ld = null; Ld = (PgpLiteralData)message; using (Stream output = File.Create(outputFile)) { Stream unc = Ld.GetInputStream(); Streams.PipeAll(unc, output); } } } else if (message is PgpLiteralData) { PgpLiteralData ld = (PgpLiteralData)message; string outFileName = ld.FileName; using (Stream fOut = File.Create(outputFile)) { Stream unc = ld.GetInputStream(); Streams.PipeAll(unc, fOut); } } else if (message is PgpOnePassSignatureList) { throw new PgpException("Encrypted message contains a signed message - not literal data."); } else { throw new PgpException("Message is not a simple encrypted file - type unknown."); } } catch (PgpException ex) { throw ex; } }
public void Decrypt(string inputFile, string outputFile) { try { PgpObjectFactory pgpF = null; PgpEncryptedDataList enc = null; PgpObject o = null; PgpPublicKeyEncryptedData pbe = null; PgpSecretKeyRingBundle pgpSec = null; pgpF = new PgpObjectFactory(PgpUtilities.GetDecoderStream(File.OpenRead(inputFile))); // find secret key pgpSec = new PgpSecretKeyRingBundle(_encriptionKeys.SecretKey.GetEncoded()); if (pgpF != null) { o = pgpF.NextPgpObject(); } // the first object might be a PGP marker packet. if (o is PgpEncryptedDataList) { enc = (PgpEncryptedDataList)o; } else { enc = (PgpEncryptedDataList)pgpF.NextPgpObject(); } foreach (PgpPublicKeyEncryptedData pked in enc.GetEncryptedDataObjects()) { var key = pgpSec.GetSecretKey(pked.KeyId); if (key != null) { pbe = pked; break; } } PgpObjectFactory plainFact = null; using (Stream clear = pbe.GetDataStream(_encriptionKeys.PrivateKey)) { plainFact = new PgpObjectFactory(clear); } PgpObject message = plainFact.NextPgpObject(); if (message is PgpCompressedData) { PgpCompressedData cData = (PgpCompressedData)message; PgpObjectFactory of = null; using (Stream compDataIn = cData.GetDataStream()) { of = new PgpObjectFactory(compDataIn); } message = of.NextPgpObject(); if (message is PgpOnePassSignatureList) { message = of.NextPgpObject(); PgpLiteralData Ld = null; Ld = (PgpLiteralData)message; using (Stream output = File.Create(outputFile)) { Stream unc = Ld.GetInputStream(); Streams.PipeAll(unc, output); } } else { PgpLiteralData Ld = null; Ld = (PgpLiteralData)message; using (Stream output = File.Create(outputFile)) { Stream unc = Ld.GetInputStream(); Streams.PipeAll(unc, output); } } } else if (message is PgpLiteralData) { PgpLiteralData ld = (PgpLiteralData)message; string outFileName = ld.FileName; using (Stream fOut = File.Create(outputFile)) { Stream unc = ld.GetInputStream(); Streams.PipeAll(unc, fOut); } } else if (message is PgpOnePassSignatureList) { throw new PgpException("Encrypted message contains a signed message - not literal data."); } else { throw new PgpException("Message is not a simple encrypted file - type unknown."); } } catch (PgpException ex) { throw ex; } }
/* * decrypt a given stream. */ public static void Decrypt(Stream inputStream, Stream privateKeyStream, string passPhrase, string outputFile) { try { PgpObjectFactory pgpF = null; PgpEncryptedDataList enc = null; PgpObject o = null; PgpPrivateKey sKey = null; PgpPublicKeyEncryptedData pbe = null; PgpSecretKeyRingBundle pgpSec = null; pgpF = new PgpObjectFactory(PgpUtilities.GetDecoderStream(inputStream)); // find secret key pgpSec = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(privateKeyStream)); if (pgpF != null) { o = pgpF.NextPgpObject(); } // the first object might be a PGP marker packet. if (o is PgpEncryptedDataList) { enc = (PgpEncryptedDataList)o; } else { enc = (PgpEncryptedDataList)pgpF.NextPgpObject(); } // decrypt foreach (PgpPublicKeyEncryptedData pked in enc.GetEncryptedDataObjects()) { sKey = FindSecretKey(pgpSec, pked.KeyId, passPhrase.ToCharArray()); if (sKey != null) { pbe = pked; break; } } if (sKey == null) { throw new ArgumentException("Secret key for message not found."); } PgpObjectFactory plainFact = null; using (Stream clear = pbe.GetDataStream(sKey)) { plainFact = new PgpObjectFactory(clear); } PgpObject message = plainFact.NextPgpObject(); if (message is PgpCompressedData) { PgpCompressedData cData = (PgpCompressedData)message; PgpObjectFactory of = null; using (Stream compDataIn = cData.GetDataStream()) { of = new PgpObjectFactory(compDataIn); } message = of.NextPgpObject(); if (message is PgpOnePassSignatureList) { message = of.NextPgpObject(); PgpLiteralData Ld = null; Ld = (PgpLiteralData)message; using (Stream output = File.Create(outputFile)) { Stream unc = Ld.GetInputStream(); Streams.PipeAll(unc, output); } } else { PgpLiteralData Ld = null; Ld = (PgpLiteralData)message; using (Stream output = File.Create(outputFile)) { Stream unc = Ld.GetInputStream(); Streams.PipeAll(unc, output); } } } else if (message is PgpLiteralData) { PgpLiteralData ld = (PgpLiteralData)message; string outFileName = ld.FileName; using (Stream fOut = File.Create(outputFile)) { Stream unc = ld.GetInputStream(); Streams.PipeAll(unc, fOut); } } else if (message is PgpOnePassSignatureList) { throw new PgpException("Encrypted message contains a signed message - not literal data."); } else { throw new PgpException("Message is not a simple encrypted file - type unknown."); } #region commented code //if (pbe.IsIntegrityProtected()) //{ // if (!pbe.Verify()) // msg = "message failed integrity check."; // //Console.Error.WriteLine("message failed integrity check"); // else // msg = "message integrity check passed."; // //Console.Error.WriteLine("message integrity check passed"); //} //else //{ // msg = "no message integrity check."; // //Console.Error.WriteLine("no message integrity check"); //} #endregion commented code } catch (PgpException ex) { throw; } }
public static byte[] DecryptPgp(byte[] input, byte[] privateKeyStream, string passPhrase) { byte[] output; using (MemoryStream inputStream = new MemoryStream(input)) { inputStream.Position = 0; PgpObjectFactory pgpFactory = new PgpObjectFactory(PgpUtilities.GetDecoderStream(inputStream)); // find secret key PgpSecretKeyRingBundle pgpKeyRing = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(new MemoryStream(privateKeyStream))); PgpObject pgp = null; if (pgpFactory != null) { pgp = pgpFactory.NextPgpObject(); } // the first object might be a PGP marker packet. PgpEncryptedDataList encryptedData = null; if (pgp is PgpEncryptedDataList) { encryptedData = (PgpEncryptedDataList)pgp; } else { encryptedData = (PgpEncryptedDataList)pgpFactory.NextPgpObject(); } // decrypt PgpPrivateKey privateKey = null; PgpPublicKeyEncryptedData pubKeyData = null; foreach (PgpPublicKeyEncryptedData pubKeyDataItem in encryptedData.GetEncryptedDataObjects()) { privateKey = FindSecretKey(pgpKeyRing, pubKeyDataItem.KeyId, passPhrase.ToCharArray()); if (privateKey != null) { pubKeyData = pubKeyDataItem; break; } } if (privateKey == null) { throw new ArgumentException("Secret key for message not found."); } PgpObjectFactory plainFact = null; using (Stream clear = pubKeyData.GetDataStream(privateKey)) { plainFact = new PgpObjectFactory(clear); } PgpObject message = plainFact.NextPgpObject(); if (message is PgpLiteralData) { PgpLiteralData literalData = (PgpLiteralData)message; using (Stream unc = literalData.GetInputStream()) using (MemoryStream outputStream = new MemoryStream()) { unc.CopyTo(outputStream); output = outputStream.ToArray(); } } else { throw new PgpException("Message is not a simple encrypted file - type unknown."); } } return(output); }