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); }
private void TestDecrypt(PgpSecretKeyRing secretKeyRing) { PgpObjectFactory pgpF = new PgpObjectFactory(testMessage); PgpEncryptedDataList encList = (PgpEncryptedDataList)pgpF.NextPgpObject(); PgpPublicKeyEncryptedData encP = (PgpPublicKeyEncryptedData)encList[0]; PgpSecretKey secretKey = secretKeyRing.GetSecretKey(); // secretKeyRing.GetSecretKey(encP.KeyId); // PgpPrivateKey pgpPrivKey = secretKey.extractPrivateKey(new JcePBESecretKeyEncryptorBuilder()); // clear = encP.getDataStream(pgpPrivKey, "BC"); // // bOut.reset(); // // while ((ch = clear.read()) >= 0) // { // bOut.write(ch); // } // // out = bOut.toByteArray(); // // if (!AreEqual(out, text)) // { // fail("wrong plain text in Generated packet"); // } }
public static PgpPublicKeyEncryptedData ExtractPublicKeyEncryptedData(System.IO.Stream encodedFile) { PgpEncryptedDataList encryptedDataList = GetEncryptedDataList(encodedFile); PgpPublicKeyEncryptedData publicKeyED = ExtractPublicKey(encryptedDataList); return(publicKeyED); }
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 void DoTestEncMessage() { PgpObjectFactory pgpFact = new PgpObjectFactory(encMessage); PgpEncryptedDataList encList = (PgpEncryptedDataList)pgpFact.NextPgpObject(); PgpPublicKeyEncryptedData encP = (PgpPublicKeyEncryptedData)encList[0]; PgpPublicKey publicKey = new PgpPublicKeyRing(testPubKey).GetPublicKey(encP.KeyId); PgpSecretKey secretKey = PgpSecretKey.ParseSecretKeyFromSExpr(new MemoryStream(sExprKeySub, false), "test".ToCharArray(), publicKey); Stream clear = encP.GetDataStream(secretKey.ExtractPrivateKey(null)); PgpObjectFactory plainFact = new PgpObjectFactory(clear); PgpCompressedData cData = (PgpCompressedData)plainFact.NextPgpObject(); PgpObjectFactory compFact = new PgpObjectFactory(cData.GetDataStream()); PgpLiteralData lData = (PgpLiteralData)compFact.NextPgpObject(); if (!"test.txt".Equals(lData.FileName)) { Fail("wrong file name detected"); } }
public static void Decrypt(Stream inputStream, Stream privateKeyStream, string passPhrase, string outputFilePath) { var objectFactory = new PgpObjectFactory(PgpUtilities.GetDecoderStream(inputStream)); var secretKeyRing = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(privateKeyStream)); PgpEncryptedDataList encryptedDataList = (objectFactory.NextPgpObject() as PgpEncryptedDataList) ?? (PgpEncryptedDataList)objectFactory.NextPgpObject(); PgpObjectFactory plainFact = RetrievePgpObjectFactory(encryptedDataList, secretKeyRing, passPhrase); PgpObject message = plainFact.NextPgpObject(); if (message is PgpOnePassSignatureList) { throw new PgpException("Encrypted message contains a signed message - not literal data."); } if (message is PgpCompressedData) { DecryptCompressedData(message, outputFilePath); } else if (message is PgpLiteralData) { PipeStreamToFile(outputFilePath, (PgpLiteralData)message); } else { throw new PgpException("Message is not a simple encrypted file - type unknown."); } }
private static PgpPublicKeyEncryptedData extractPublicKeyEncryptedData(Stream inputStream) { Stream encodedFile = PgpUtilities.GetDecoderStream(inputStream); PgpEncryptedDataList encryptedDataList = getEncryptedDataList(encodedFile); PgpPublicKeyEncryptedData publicKeyED = extractPublicKey(encryptedDataList); return(publicKeyED); }
public static PgpPublicKeyEncryptedData ExtractPublicKeyEncryptedData(System.IO.Stream inputStream) { System.IO.Stream encodedFile = PgpUtilities.GetDecoderStream(inputStream); PgpEncryptedDataList encryptedDataList = GetEncryptedDataList(encodedFile); PgpPublicKeyEncryptedData publicKeyED = ExtractPublicKey(encryptedDataList); return(publicKeyED); }
public String DecryptMessage(String encryptedMessage, char[] passPhrase) { // Remove the Base64 encoding byte[] rawMessage = Convert.FromBase64String(encryptedMessage); 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(); } PgpPbeEncryptedData pbe = (PgpPbeEncryptedData)enc[0]; Stream clear = pbe.GetDataStream(passPhrase); PgpObjectFactory pgpFact = new PgpObjectFactory(clear); PgpLiteralData ld = (PgpLiteralData)pgpFact.NextPgpObject(); Stream unc = ld.GetInputStream(); String message; using (StreamReader reader = new StreamReader(unc, Encoding.UTF8)) { message = reader.ReadToEnd(); } // Finally verify the integrity if (pbe.IsIntegrityProtected()) { if (!pbe.Verify()) { throw new MessageVerificationException("Failed to verify the message. It might have been modified in transit."); } } return(message); }
private void DoTestSignedEncMessage() { PgpObjectFactory pgpFact = new PgpObjectFactory(signedEncMessage); PgpEncryptedDataList encList = (PgpEncryptedDataList)pgpFact.NextPgpObject(); PgpPublicKeyEncryptedData encP = (PgpPublicKeyEncryptedData)encList[0]; PgpPublicKeyRing publicKeyRing = new PgpPublicKeyRing(testPubKey); PgpPublicKey publicKey = publicKeyRing.GetPublicKey(encP.KeyId); PgpSecretKey secretKey = PgpSecretKey.ParseSecretKeyFromSExpr(new MemoryStream(sExprKeySub, false), "test".ToCharArray(), publicKey); Stream clear = encP.GetDataStream(secretKey.ExtractPrivateKey(null)); PgpObjectFactory plainFact = new PgpObjectFactory(clear); PgpCompressedData cData = (PgpCompressedData)plainFact.NextPgpObject(); PgpObjectFactory compFact = new PgpObjectFactory(cData.GetDataStream()); PgpOnePassSignatureList sList = (PgpOnePassSignatureList)compFact.NextPgpObject(); PgpOnePassSignature ops = sList[0]; PgpLiteralData lData = (PgpLiteralData)compFact.NextPgpObject(); if (!"test.txt".Equals(lData.FileName)) { Fail("wrong file name detected"); } Stream dIn = lData.GetInputStream(); ops.InitVerify(publicKeyRing.GetPublicKey(ops.KeyId)); int ch; while ((ch = dIn.ReadByte()) >= 0) { ops.Update((byte)ch); } PgpSignatureList p3 = (PgpSignatureList)compFact.NextPgpObject(); if (!ops.Verify(p3[0])) { Fail("Failed signature check"); } }
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); }
public void DecryptFile(Stream outStream, Stream inputStream, char[] passPhrase) { 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(); } PgpPbeEncryptedData pbe = (PgpPbeEncryptedData)enc[0]; Stream clear = pbe.GetDataStream(passPhrase); PgpObjectFactory pgpFact = new PgpObjectFactory(clear); PgpLiteralData ld = (PgpLiteralData)pgpFact.NextPgpObject(); Stream unc = ld.GetInputStream(); byte[] buf = new byte[1 << 16]; int len; while ((len = unc.Read(buf, 0, buf.Length)) > 0) { outStream.Write(buf, 0, len); } // Finally verify the integrity if (pbe.IsIntegrityProtected()) { if (!pbe.Verify()) { throw new MessageVerificationException("Failed to verify the message. It might have been modified in transit."); } } }
private byte[] DecryptMessageBuffered( byte[] message) { PgpObjectFactory pgpF = new PgpObjectFactory(message); PgpEncryptedDataList enc = (PgpEncryptedDataList)pgpF.NextPgpObject(); PgpPbeEncryptedData pbe = (PgpPbeEncryptedData)enc[0]; Stream clear = pbe.GetDataStream(pass); PgpObjectFactory pgpFact = new PgpObjectFactory(clear); PgpCompressedData cData = (PgpCompressedData)pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(cData.GetDataStream()); PgpLiteralData ld = (PgpLiteralData)pgpFact.NextPgpObject(); MemoryStream bOut = new MemoryStream(); if (!ld.FileName.Equals("test.txt") && !ld.FileName.Equals("_CONSOLE")) { Fail("wrong filename in packet"); } if (!ld.ModificationTime.Equals(TestDateTime)) { Fail("wrong modification time in packet: " + ld.ModificationTime.Ticks + " " + TestDateTime.Ticks); } Stream unc = ld.GetInputStream(); byte[] buf = new byte[1024]; int len; while ((len = unc.Read(buf, 0, buf.Length)) > 0) { bOut.Write(buf, 0, len); } if (pbe.IsIntegrityProtected() && !pbe.Verify()) { Fail("integrity check failed"); } return(bOut.ToArray()); }
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("未能正常读取到加密文件内容,请检查文件及密钥"); }
/** * decrypt the passed in message stream * * @param encrypted The message to be decrypted. * @param passPhrase Pass phrase (key) * * @return Clear text as a byte array. I18N considerations are * not handled by this routine * @exception IOException * @exception PgpException */ public static byte[] Decrypt( byte[] encrypted, char[] passPhrase) { Stream inputStream = new MemoryStream(encrypted); 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(); } PgpPbeEncryptedData pbe = (PgpPbeEncryptedData)enc[0]; Stream clear = pbe.GetDataStream(passPhrase); PgpObjectFactory pgpFact = new PgpObjectFactory(clear); PgpCompressedData cData = (PgpCompressedData)pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(cData.GetDataStream()); PgpLiteralData ld = (PgpLiteralData)pgpFact.NextPgpObject(); Stream unc = ld.GetInputStream(); return(Streams.ReadAll(unc)); }
/** * decrypt the passed in message stream */ private byte[] DecryptMessage( byte[] message) { PgpObjectFactory pgpF = new PgpObjectFactory(message); PgpEncryptedDataList enc = (PgpEncryptedDataList)pgpF.NextPgpObject(); PgpPbeEncryptedData pbe = (PgpPbeEncryptedData)enc[0]; Stream clear = pbe.GetDataStream(pass); PgpObjectFactory pgpFact = new PgpObjectFactory(clear); PgpCompressedData cData = (PgpCompressedData)pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(cData.GetDataStream()); PgpLiteralData ld = (PgpLiteralData)pgpFact.NextPgpObject(); if (!ld.FileName.Equals("test.txt") && !ld.FileName.Equals("_CONSOLE")) { Fail("wrong filename in packet"); } if (!ld.ModificationTime.Equals(TestDateTime)) { Fail("wrong modification time in packet: " + ld.ModificationTime + " vs " + TestDateTime); } Stream unc = ld.GetInputStream(); byte[] bytes = Streams.ReadAll(unc); if (pbe.IsIntegrityProtected() && !pbe.Verify()) { Fail("integrity check failed"); } return(bytes); }
/* * 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."); } }
public override void PerformTest() { // // Read the public key // PgpObjectFactory pgpFact = new PgpObjectFactory(testPubKeyRing); PgpPublicKeyRing pgpPub = (PgpPublicKeyRing)pgpFact.NextPgpObject(); var pubKey = pgpPub.GetPublicKey(); if (pubKey.BitStrength != 1024) { Fail("failed - key strength reported incorrectly."); } // // Read the private key // PgpSecretKeyRing sKey = new PgpSecretKeyRing(testPrivKeyRing); IPgpSecretKey secretKey = sKey.GetSecretKey(); IPgpPrivateKey pgpPrivKey = secretKey.ExtractPrivateKey(pass); // // signature generation // const string data = "hello world!"; byte[] dataBytes = Encoding.ASCII.GetBytes(data); MemoryStream bOut = new MemoryStream(); MemoryStream testIn = new MemoryStream(dataBytes, false); PgpSignatureGenerator sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1); sGen.InitSign(PgpSignature.BinaryDocument, pgpPrivKey); PgpCompressedDataGenerator cGen = new PgpCompressedDataGenerator( CompressionAlgorithmTag.Zip); BcpgOutputStream bcOut = new BcpgOutputStream( cGen.Open(new UncloseableStream(bOut))); sGen.GenerateOnePassVersion(false).Encode(bcOut); PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator(); DateTime testDateTime = new DateTime(1973, 7, 27); Stream lOut = lGen.Open( new UncloseableStream(bcOut), PgpLiteralData.Binary, "_CONSOLE", dataBytes.Length, testDateTime); int ch; while ((ch = testIn.ReadByte()) >= 0) { lOut.WriteByte((byte)ch); sGen.Update((byte)ch); } lGen.Close(); sGen.Generate().Encode(bcOut); cGen.Close(); // // verify Generated signature // pgpFact = new PgpObjectFactory(bOut.ToArray()); PgpCompressedData c1 = (PgpCompressedData)pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(c1.GetDataStream()); PgpOnePassSignatureList p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject(); PgpOnePassSignature ops = p1[0]; PgpLiteralData p2 = (PgpLiteralData)pgpFact.NextPgpObject(); if (!p2.ModificationTime.Equals(testDateTime)) { Fail("Modification time not preserved"); } Stream dIn = p2.GetInputStream(); ops.InitVerify(pubKey); while ((ch = dIn.ReadByte()) >= 0) { ops.Update((byte)ch); } PgpSignatureList p3 = (PgpSignatureList)pgpFact.NextPgpObject(); if (!ops.Verify(p3[0])) { Fail("Failed Generated signature check"); } // // test encryption // // // find a key sutiable for encryption // long pgpKeyID = 0; IAsymmetricKeyParameter pKey = null; foreach (PgpPublicKey pgpKey in pgpPub.GetPublicKeys()) { if (pgpKey.Algorithm == PublicKeyAlgorithmTag.ElGamalEncrypt || pgpKey.Algorithm == PublicKeyAlgorithmTag.ElGamalGeneral) { pKey = pgpKey.GetKey(); pgpKeyID = pgpKey.KeyId; if (pgpKey.BitStrength != 1024) { Fail("failed - key strength reported incorrectly."); } // // verify the key // } } IBufferedCipher c = CipherUtilities.GetCipher("ElGamal/None/PKCS1Padding"); c.Init(true, pKey); byte[] inBytes = Encoding.ASCII.GetBytes("hello world"); byte[] outBytes = c.DoFinal(inBytes); pgpPrivKey = sKey.GetSecretKey(pgpKeyID).ExtractPrivateKey(pass); c.Init(false, pgpPrivKey.Key); outBytes = c.DoFinal(outBytes); if (!Arrays.AreEqual(inBytes, outBytes)) { Fail("decryption failed."); } // // encrypted message // byte[] text = { (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o', (byte)' ', (byte)'w', (byte)'o', (byte)'r', (byte)'l',(byte)'d', (byte)'!', (byte)'\n' }; PgpObjectFactory pgpF = new PgpObjectFactory(encMessage); PgpEncryptedDataList encList = (PgpEncryptedDataList)pgpF.NextPgpObject(); PgpPublicKeyEncryptedData encP = (PgpPublicKeyEncryptedData)encList[0]; Stream clear = encP.GetDataStream(pgpPrivKey); pgpFact = new PgpObjectFactory(clear); c1 = (PgpCompressedData)pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(c1.GetDataStream()); PgpLiteralData ld = (PgpLiteralData)pgpFact.NextPgpObject(); if (!ld.FileName.Equals("test.txt")) { throw new Exception("wrong filename in packet"); } Stream inLd = ld.GetDataStream(); byte[] bytes = Streams.ReadAll(inLd); if (!Arrays.AreEqual(bytes, text)) { Fail("wrong plain text in decrypted packet"); } // // signed and encrypted message // pgpF = new PgpObjectFactory(signedAndEncMessage); encList = (PgpEncryptedDataList)pgpF.NextPgpObject(); encP = (PgpPublicKeyEncryptedData)encList[0]; clear = encP.GetDataStream(pgpPrivKey); pgpFact = new PgpObjectFactory(clear); c1 = (PgpCompressedData)pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(c1.GetDataStream()); p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject(); ops = p1[0]; ld = (PgpLiteralData)pgpFact.NextPgpObject(); bOut = new MemoryStream(); if (!ld.FileName.Equals("test.txt")) { throw new Exception("wrong filename in packet"); } inLd = ld.GetDataStream(); // // note: we use the DSA public key here. // ops.InitVerify(pgpPub.GetPublicKey()); while ((ch = inLd.ReadByte()) >= 0) { ops.Update((byte)ch); bOut.WriteByte((byte)ch); } p3 = (PgpSignatureList)pgpFact.NextPgpObject(); if (!ops.Verify(p3[0])) { Fail("Failed signature check"); } if (!Arrays.AreEqual(bOut.ToArray(), text)) { Fail("wrong plain text in decrypted packet"); } // // encrypt // MemoryStream cbOut = new MemoryStream(); PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator( SymmetricKeyAlgorithmTag.TripleDes, random); IPgpPublicKey puK = sKey.GetSecretKey(pgpKeyID).PublicKey; cPk.AddMethod(puK); Stream cOut = cPk.Open(new UncloseableStream(cbOut), bOut.ToArray().Length); cOut.Write(text, 0, text.Length); cOut.Close(); pgpF = new PgpObjectFactory(cbOut.ToArray()); encList = (PgpEncryptedDataList)pgpF.NextPgpObject(); encP = (PgpPublicKeyEncryptedData)encList[0]; pgpPrivKey = sKey.GetSecretKey(pgpKeyID).ExtractPrivateKey(pass); clear = encP.GetDataStream(pgpPrivKey); outBytes = Streams.ReadAll(clear); if (!Arrays.AreEqual(outBytes, text)) { Fail("wrong plain text in Generated packet"); } // // use of PgpKeyPair // IBigInteger g = new BigInteger("153d5d6172adb43045b68ae8e1de1070b6137005686d29d3d73a7749199681ee5b212c9b96bfdcfa5b20cd5e3fd2044895d609cf9b410b7a0f12ca1cb9a428cc", 16); IBigInteger p = new BigInteger("9494fec095f3b85ee286542b3836fc81a5dd0a0349b4c239dd38744d488cf8e31db8bcb7d33b41abb9e5a33cca9144b1cef332c94bf0573bf047a3aca98cdf3b", 16); ElGamalParameters elParams = new ElGamalParameters(p, g); IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator("ELGAMAL"); kpg.Init(new ElGamalKeyGenerationParameters(random, elParams)); IAsymmetricCipherKeyPair kp = kpg.GenerateKeyPair(); PgpKeyPair pgpKp = new PgpKeyPair(PublicKeyAlgorithmTag.ElGamalGeneral, kp.Public, kp.Private, DateTime.UtcNow); PgpPublicKey k1 = pgpKp.PublicKey; PgpPrivateKey k2 = pgpKp.PrivateKey; // Test bug with ElGamal P size != 0 mod 8 (don't use these sizes at home!) for (int pSize = 257; pSize < 264; ++pSize) { // Generate some parameters of the given size ElGamalParametersGenerator epg = new ElGamalParametersGenerator(); epg.Init(pSize, 2, random); elParams = epg.GenerateParameters(); kpg = GeneratorUtilities.GetKeyPairGenerator("ELGAMAL"); kpg.Init(new ElGamalKeyGenerationParameters(random, elParams)); // Run a short encrypt/decrypt test with random key for the given parameters kp = kpg.GenerateKeyPair(); PgpKeyPair elGamalKeyPair = new PgpKeyPair( PublicKeyAlgorithmTag.ElGamalGeneral, kp, DateTime.UtcNow); cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, random); puK = elGamalKeyPair.PublicKey; cPk.AddMethod(puK); cbOut = new MemoryStream(); cOut = cPk.Open(new UncloseableStream(cbOut), text.Length); cOut.Write(text, 0, text.Length); cOut.Close(); pgpF = new PgpObjectFactory(cbOut.ToArray()); encList = (PgpEncryptedDataList)pgpF.NextPgpObject(); encP = (PgpPublicKeyEncryptedData)encList[0]; pgpPrivKey = elGamalKeyPair.PrivateKey; // Note: This is where an exception would be expected if the P size causes problems clear = encP.GetDataStream(pgpPrivKey); byte[] decText = Streams.ReadAll(clear); if (!Arrays.AreEqual(text, decText)) { Fail("decrypted message incorrect"); } } // check sub key encoding foreach (PgpPublicKey pgpKey in pgpPub.GetPublicKeys()) { if (!pgpKey.IsMasterKey) { byte[] kEnc = pgpKey.GetEncoded(); PgpObjectFactory objF = new PgpObjectFactory(kEnc); // TODO Make PgpPublicKey a PgpObject or return a PgpPublicKeyRing // PgpPublicKey k = (PgpPublicKey)objF.NextPgpObject(); // // pKey = k.GetKey(); // pgpKeyID = k.KeyId; // if (k.BitStrength != 1024) // { // Fail("failed - key strength reported incorrectly."); // } // // if (objF.NextPgpObject() != null) // { // Fail("failed - stream not fully parsed."); // } } } }
/// <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 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; } }
/// <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); }
/** * decrypt the passed in message stream */ private static void DecryptFile( Stream inputStream, char[] passPhrase) { inputStream = PgpUtilities.GetDecoderStream(inputStream); PgpObjectFactory pgpF = new PgpObjectFactory(inputStream); PgpObject o = pgpF.NextPgpObject(); // // the first object might be a PGP marker packet. // PgpEncryptedDataList enc = o as PgpEncryptedDataList; if (enc == null) { enc = (PgpEncryptedDataList)pgpF.NextPgpObject(); } PgpPbeEncryptedData pbe = (PgpPbeEncryptedData)enc[0]; Stream clear = pbe.GetDataStream(passPhrase); PgpObjectFactory pgpFact = new PgpObjectFactory(clear); // // if we're trying to read a file generated by someone other than us // the data might not be compressed, so we check the return type from // the factory and behave accordingly. // o = pgpFact.NextPgpObject(); if (o is PgpCompressedData) { PgpCompressedData cData = (PgpCompressedData)o; pgpFact = new PgpObjectFactory(cData.GetDataStream()); o = pgpFact.NextPgpObject(); } PgpLiteralData ld = (PgpLiteralData)o; Stream unc = ld.GetInputStream(); Stream fOut = File.Create(ld.FileName); Streams.PipeAll(unc, fOut); fOut.Close(); if (pbe.IsIntegrityProtected()) { if (!pbe.Verify()) { Console.Error.WriteLine("message failed integrity check"); } else { Console.Error.WriteLine("message integrity check passed"); } } else { Console.Error.WriteLine("no message integrity check"); } }
private void EncryptDecryptTest() { SecureRandom random = SecureRandom.GetInstance("SHA1PRNG"); byte[] text = Encoding.ASCII.GetBytes("hello world!"); IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator("ECDH"); keyGen.Init(new ECKeyGenerationParameters(SecObjectIdentifiers.SecP256r1, random)); AsymmetricCipherKeyPair kpEnc = keyGen.GenerateKeyPair(); PgpKeyPair ecdhKeyPair = new PgpKeyPair(PublicKeyAlgorithmTag.ECDH, kpEnc, DateTime.UtcNow); PgpLiteralDataGenerator lData = new PgpLiteralDataGenerator(); MemoryStream ldOut = new MemoryStream(); Stream pOut = lData.Open(ldOut, PgpLiteralDataGenerator.Utf8, PgpLiteralData.Console, text.Length, DateTime.UtcNow); pOut.Write(text, 0, text.Length); pOut.Close(); byte[] data = ldOut.ToArray(); MemoryStream cbOut = new MemoryStream(); PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, random); cPk.AddMethod(ecdhKeyPair.PublicKey); Stream cOut = cPk.Open(new UncloseableStream(cbOut), data.Length); cOut.Write(data, 0, data.Length); cOut.Close(); PgpObjectFactory pgpF = new PgpObjectFactory(cbOut.ToArray()); PgpEncryptedDataList encList = (PgpEncryptedDataList)pgpF.NextPgpObject(); PgpPublicKeyEncryptedData encP = (PgpPublicKeyEncryptedData)encList[0]; Stream clear = encP.GetDataStream(ecdhKeyPair.PrivateKey); pgpF = new PgpObjectFactory(clear); PgpLiteralData ld = (PgpLiteralData)pgpF.NextPgpObject(); clear = ld.GetInputStream(); MemoryStream bOut = new MemoryStream(); int ch; while ((ch = clear.ReadByte()) >= 0) { bOut.WriteByte((byte)ch); } byte[] output = bOut.ToArray(); if (!AreEqual(output, text)) { Fail("wrong plain text in Generated packet"); } }
public override void PerformTest() { byte[] data = DecryptMessage(enc1); if (data[0] != 'h' || data[1] != 'e' || data[2] != 'l') { Fail("wrong plain text in packet"); } // // create a PBE encrypted message and read it back. // byte[] text = Encoding.ASCII.GetBytes("hello world!\n"); // // encryption step - convert to literal data, compress, encode. // MemoryStream bOut = new UncloseableMemoryStream(); PgpCompressedDataGenerator comData = new PgpCompressedDataGenerator( CompressionAlgorithmTag.Zip); PgpLiteralDataGenerator lData = new PgpLiteralDataGenerator(); Stream comOut = comData.Open(new UncloseableStream(bOut)); Stream ldOut = lData.Open( new UncloseableStream(comOut), PgpLiteralData.Binary, PgpLiteralData.Console, text.Length, TestDateTime); ldOut.Write(text, 0, text.Length); ldOut.Close(); comOut.Close(); // // encrypt - with stream close // MemoryStream cbOut = new UncloseableMemoryStream(); PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator( SymmetricKeyAlgorithmTag.Cast5, new SecureRandom()); cPk.AddMethod(pass, HashAlgorithmTag.Sha1); byte[] bOutData = bOut.ToArray(); Stream cOut = cPk.Open(new UncloseableStream(cbOut), bOutData.Length); cOut.Write(bOutData, 0, bOutData.Length); cOut.Close(); data = DecryptMessage(cbOut.ToArray()); if (!Arrays.AreEqual(data, text)) { Fail("wrong plain text in generated packet"); } // // encrypt - with generator close // cbOut = new UncloseableMemoryStream(); cPk = new PgpEncryptedDataGenerator( SymmetricKeyAlgorithmTag.Cast5, new SecureRandom()); cPk.AddMethod(pass, HashAlgorithmTag.Sha1); bOutData = bOut.ToArray(); cOut = cPk.Open(new UncloseableStream(cbOut), bOutData.Length); cOut.Write(bOutData, 0, bOutData.Length); cPk.Close(); data = DecryptMessage(cbOut.ToArray()); if (!AreEqual(data, text)) { Fail("wrong plain text in generated packet"); } // // encrypt - partial packet style. // SecureRandom rand = new SecureRandom(); byte[] test = new byte[1233]; rand.NextBytes(test); bOut = new UncloseableMemoryStream(); comData = new PgpCompressedDataGenerator( CompressionAlgorithmTag.Zip); comOut = comData.Open(new UncloseableStream(bOut)); lData = new PgpLiteralDataGenerator(); ldOut = lData.Open( new UncloseableStream(comOut), PgpLiteralData.Binary, PgpLiteralData.Console, TestDateTime, new byte[16]); ldOut.Write(test, 0, test.Length); lData.Close(); comData.Close(); cbOut = new UncloseableMemoryStream(); cPk = new PgpEncryptedDataGenerator( SymmetricKeyAlgorithmTag.Cast5, rand); cPk.AddMethod(pass, HashAlgorithmTag.Sha1); cOut = cPk.Open(new UncloseableStream(cbOut), new byte[16]); { byte[] tmp = bOut.ToArray(); cOut.Write(tmp, 0, tmp.Length); } cPk.Close(); data = DecryptMessage(cbOut.ToArray()); if (!Arrays.AreEqual(data, test)) { Fail("wrong plain text in generated packet"); } // // with integrity packet // cbOut = new UncloseableMemoryStream(); cPk = new PgpEncryptedDataGenerator( SymmetricKeyAlgorithmTag.Cast5, true, rand); cPk.AddMethod(pass, HashAlgorithmTag.Sha1); cOut = cPk.Open(new UncloseableStream(cbOut), new byte[16]); bOutData = bOut.ToArray(); cOut.Write(bOutData, 0, bOutData.Length); cPk.Close(); data = DecryptMessage(cbOut.ToArray()); if (!Arrays.AreEqual(data, test)) { Fail("wrong plain text in generated packet"); } // // decrypt with buffering // data = DecryptMessageBuffered(cbOut.ToArray()); if (!AreEqual(data, test)) { Fail("wrong plain text in buffer generated packet"); } // // sample message // PgpObjectFactory pgpFact = new PgpObjectFactory(testPBEAsym); PgpEncryptedDataList enc = (PgpEncryptedDataList)pgpFact.NextPgpObject(); PgpPbeEncryptedData pbe = (PgpPbeEncryptedData)enc[1]; Stream clear = pbe.GetDataStream("password".ToCharArray()); pgpFact = new PgpObjectFactory(clear); PgpLiteralData ld = (PgpLiteralData)pgpFact.NextPgpObject(); Stream unc = ld.GetInputStream(); byte[] bytes = Streams.ReadAll(unc); if (!AreEqual(bytes, Hex.Decode("5361742031302e30322e30370d0a"))) { Fail("data mismatch on combined PBE"); } // // with integrity packet - one byte message // byte[] msg = new byte[1]; bOut = new MemoryStream(); comData = new PgpCompressedDataGenerator( CompressionAlgorithmTag.Zip); lData = new PgpLiteralDataGenerator(); comOut = comData.Open(new UncloseableStream(bOut)); ldOut = lData.Open( new UncloseableStream(comOut), PgpLiteralData.Binary, PgpLiteralData.Console, msg.Length, TestDateTime); ldOut.Write(msg, 0, msg.Length); ldOut.Close(); comOut.Close(); cbOut = new MemoryStream(); cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, true, rand); cPk.AddMethod(pass, HashAlgorithmTag.Sha1); cOut = cPk.Open(new UncloseableStream(cbOut), new byte[16]); data = bOut.ToArray(); cOut.Write(data, 0, data.Length); cOut.Close(); data = DecryptMessage(cbOut.ToArray()); if (!AreEqual(data, msg)) { Fail("wrong plain text in generated packet"); } // // decrypt with buffering // data = DecryptMessageBuffered(cbOut.ToArray()); if (!AreEqual(data, msg)) { Fail("wrong plain text in buffer generated packet"); } }
public static PgpPublicKeyEncryptedData ExtractPublicKeyEncryptedData(PgpEncryptedDataList encryptedDataList) { PgpPublicKeyEncryptedData publicKeyED = ExtractPublicKey(encryptedDataList); return(publicKeyED); }
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); }
/* * 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; } }
/// <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(); }