private static void VerifySignature(PgpOnePassSignatureList onePassSigList, PgpSignatureList signatureList, PgpPublicKey pubKey, byte[] original) { PgpOnePassSignature ops = onePassSigList[0]; ops.InitVerify(pubKey); ops.Update(original); PgpSignatureList p3 = signatureList; PgpSignature sig = p3[0]; if (sig.KeyId != pubKey.KeyId) { throw new PgpException("key id mismatch in signature."); } if (!ops.Verify(sig)) { throw new PgpException("Failed generated signature check."); } sig.InitVerify(pubKey); for (int i = 0; i < original.Length; i++) { sig.Update(original[i]); } //sig.Update(original); if (!sig.Verify()) { throw new PgpException("Failed generated signature check against original data."); } }
private void doSigVerifyTest( string publicKeyFile, string sigFile) { PgpPublicKeyRing publicKey = loadPublicKey(publicKeyFile); PgpObjectFactory pgpFact = loadSig(sigFile); PgpCompressedData c1 = (PgpCompressedData)pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(c1.GetDataStream()); PgpOnePassSignatureList p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject(); PgpOnePassSignature ops = p1[0]; PgpLiteralData p2 = (PgpLiteralData)pgpFact.NextPgpObject(); Stream dIn = p2.GetInputStream(); ops.InitVerify(publicKey.GetPublicKey()); int ch; while ((ch = dIn.ReadByte()) >= 0) { ops.Update((byte)ch); } PgpSignatureList p3 = (PgpSignatureList)pgpFact.NextPgpObject(); Assert.IsTrue(ops.Verify(p3[0])); }
/// <summary> /// Initialise the one-pass signature from the literal block. /// </summary> /// <param name="publicKeyStream"> /// The stream containing the public stream. /// </param> /// <param name="onePassSignatureList"> /// One-pass signature list. /// </param> /// <param name="publicKey"> /// Public key for validating the signature. /// </param> /// <returns> /// Returns the one-pass signature. /// </returns> private static PgpOnePassSignature InitOnePassSignatureFromLiteral( Stream publicKeyStream, PgpOnePassSignatureList onePassSignatureList, ref PgpPublicKey publicKey) { if (onePassSignatureList == null) { throw new PgpException("One pass signature not found."); } var onePassSignature = onePassSignatureList[0]; Console.WriteLine("verifier : " + onePassSignature.KeyId.ToString("X")); var publicKeyringBundle = new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(publicKeyStream)); publicKey = publicKeyringBundle.GetPublicKey(onePassSignature.KeyId); if (publicKey == null) { throw new PgpException("No public key for signature validation"); } onePassSignature.InitVerify(publicKey); return(onePassSignature); }
/// <summary> /// Verifies a PGP signature. See documentation at https://github.com/CommunityHiQ/Frends.Community.PgpVerifySignature Returns: Object {string FilePath, Boolean Verified} /// </summary> public static Result PGPVerifySignFile(Input input) { try { Stream inputStream = PgpUtilities.GetDecoderStream(File.OpenRead(input.InputFile)); PgpObjectFactory pgpFact = new PgpObjectFactory(inputStream); PgpOnePassSignatureList p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject(); PgpOnePassSignature ops = p1[0]; PgpLiteralData p2 = (PgpLiteralData)pgpFact.NextPgpObject(); Stream dIn = p2.GetInputStream(); PgpPublicKeyRingBundle pgpRing = new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(File.OpenRead(input.PublicKeyFile))); PgpPublicKey key = pgpRing.GetPublicKey(ops.KeyId); string fosPath; if (String.IsNullOrWhiteSpace(input.OutputFolder)) { fosPath = Path.Combine(Path.GetDirectoryName(input.InputFile), p2.FileName); } else { fosPath = Path.Combine(input.OutputFolder, p2.FileName); } Stream fos = File.Create(fosPath); ops.InitVerify(key); int ch; while ((ch = dIn.ReadByte()) >= 0) { ops.Update((byte)ch); fos.WriteByte((byte)ch); } fos.Close(); PgpSignatureList p3 = (PgpSignatureList)pgpFact.NextPgpObject(); PgpSignature firstSig = p3[0]; bool verified = ops.Verify(firstSig); Result ret = new Result { FilePath = fosPath, Verified = verified }; return(ret); } catch (Exception e) { Result ret = new Result { FilePath = input.OutputFolder, Verified = false }; return(ret); } }
/// <summary> /// Verifies the specified signature using the specified public key. /// </summary> /// <param name="input">The signature to verify.</param> /// <param name="publicKey">The public key with which to decode the signature.</param> /// <returns>A byte array containing the message contained within the signature.</returns> /// <exception cref="PgpDataValidationException"> /// Thrown when the specified signature is invalid, or if an exception is encountered while validating. /// </exception> public static byte[] Verify(string input, string publicKey) { // create input streams from Stream inputStream = new MemoryStream(Encoding.UTF8.GetBytes(input ?? string.Empty)); Stream publicKeyStream = new MemoryStream(Encoding.UTF8.GetBytes(publicKey ?? string.Empty)); // enclose all operations in a try/catch. if we encounter any exceptions verification fails. try { // lines taken pretty much verbatim from the bouncycastle example. not sure what it all does. inputStream = PgpUtilities.GetDecoderStream(inputStream); PgpObjectFactory pgpFact = new PgpObjectFactory(inputStream); PgpCompressedData c1 = (PgpCompressedData)pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(c1.GetDataStream()); PgpOnePassSignatureList p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject(); PgpOnePassSignature ops = p1[0]; PgpLiteralData p2 = (PgpLiteralData)pgpFact.NextPgpObject(); Stream dIn = p2.GetInputStream(); PgpPublicKeyRingBundle pgpRing = new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(publicKeyStream)); PgpPublicKey key = pgpRing.GetPublicKey(ops.KeyId); // set up a memorystream to contain the message contained within the signature MemoryStream memoryStream = new MemoryStream(); ops.InitVerify(key); int ch; while ((ch = dIn.ReadByte()) >= 0) { ops.Update((byte)ch); memoryStream.WriteByte((byte)ch); } // save the contents of the memorystream to a byte array byte[] retVal = memoryStream.ToArray(); memoryStream.Close(); PgpSignatureList p3 = (PgpSignatureList)pgpFact.NextPgpObject(); PgpSignature firstSig = p3[0]; // verify. if (ops.Verify(firstSig)) { return(retVal); } else { throw new PgpDataValidationException(); } } catch (Exception) { throw new PgpDataValidationException(); } }
private void verifySignature( byte[] encodedSig, HashAlgorithmTag hashAlgorithm, PgpPublicKey pubKey, byte[] original) { PgpObjectFactory pgpFact = new PgpObjectFactory(encodedSig); PgpOnePassSignatureList p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject(); PgpOnePassSignature ops = p1[0]; PgpLiteralData p2 = (PgpLiteralData)pgpFact.NextPgpObject(); Stream dIn = p2.GetInputStream(); ops.InitVerify(pubKey); int ch; while ((ch = dIn.ReadByte()) >= 0) { ops.Update((byte)ch); } PgpSignatureList p3 = (PgpSignatureList)pgpFact.NextPgpObject(); PgpSignature sig = p3[0]; DateTime creationTime = sig.CreationTime; // Check creationTime is recent if (creationTime.CompareTo(DateTime.UtcNow) > 0 || creationTime.CompareTo(DateTime.UtcNow.AddMinutes(-10)) < 0) { Fail("bad creation time in signature: " + creationTime); } if (sig.KeyId != pubKey.KeyId) { Fail("key id mismatch in signature"); } if (!ops.Verify(sig)) { Fail("Failed generated signature check - " + hashAlgorithm); } sig.InitVerify(pubKey); for (int i = 0; i != original.Length; i++) { sig.Update(original[i]); } sig.Update(original); if (!sig.Verify()) { Fail("Failed generated signature check against original data"); } }
public static bool Verify(string hash, string signature, string publicKey) { try { var signatureStream = new MemoryStream(Encoding.ASCII.GetBytes(signature)); var decoderStream = PgpUtilities.GetDecoderStream(signatureStream); PgpObjectFactory pgpObjectFactory = new PgpObjectFactory(decoderStream); PgpOnePassSignatureList signatureList = (PgpOnePassSignatureList)pgpObjectFactory.NextPgpObject(); PgpOnePassSignature onePassSignature = signatureList[0]; PgpLiteralData literalData = (PgpLiteralData)pgpObjectFactory.NextPgpObject(); Stream literalStream = literalData.GetInputStream(); Stream keyFile = new MemoryStream(Encoding.ASCII.GetBytes(publicKey)); PgpPublicKeyRingBundle pgpRing = new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(keyFile)); PgpPublicKey key = pgpRing.GetPublicKey(onePassSignature.KeyId); Stream outStream = new MemoryStream(); onePassSignature.InitVerify(key); int ch; while ((ch = literalStream.ReadByte()) >= 0) { onePassSignature.Update((byte)ch); outStream.WriteByte((byte)ch); } var hashStream = new MemoryStream(Encoding.ASCII.GetBytes(hash)); outStream.Seek(0, SeekOrigin.Begin); if (hashStream.Length != outStream.Length) { return(false); } int left, right; while ((left = hashStream.ReadByte()) >= 0 && (right = outStream.ReadByte()) >= 0) { if (left != right) { return(false); } } outStream.Dispose(); PgpSignatureList signatureList2 = (PgpSignatureList)pgpObjectFactory.NextPgpObject(); PgpSignature firstSig = signatureList2[0]; if (onePassSignature.Verify(firstSig)) { return(true); } else { return(false); } } catch { return(false); } }
private SignatureStatus VerifyFileSignature(Stream literalDataStream, PgpOnePassSignatureList pgpOnePassSignatureList, PgpSignatureList pgpSignatureList) { try { const int BUFFER_SIZE = 1 << 16; // should always be power of 2 SignatureStatus signatureStatus = SignatureStatus.Invalid; var signatureKeys = GetAllSignatureKeys(); if (pgpOnePassSignatureList == null) { return(SignatureStatus.NoSignature); } for (int i = 0; i < pgpOnePassSignatureList.Count; i++) { if (literalDataStream.CanSeek) { literalDataStream.Seek(0, SeekOrigin.Begin); } PgpOnePassSignature pgpOnePassSignature = pgpOnePassSignatureList[i]; Stream dIn = literalDataStream; var keyIn = FindSignatureKey(signatureKeys, pgpOnePassSignature.KeyId); if (keyIn == null) { continue; } pgpOnePassSignature.InitVerify(keyIn); byte[] buf = new byte[BUFFER_SIZE]; int len; while ((len = dIn.Read(buf, 0, buf.Length)) > 0) { pgpOnePassSignature.Update(buf, 0, len); } PgpSignature pgpSignature = pgpSignatureList[i]; if (pgpOnePassSignature.Verify(pgpSignature)) { signatureStatus = SignatureStatus.Valid; break; } } return(signatureStatus); } catch { return(SignatureStatus.Error); } }
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"); } }
/// <summary> /// Process each message block type depending on the type. /// </summary> /// <param name="encryptedData"> /// Encrypted data packets. /// </param> /// <param name="outputStream"> /// Stream to write output. /// </param> /// <param name="publicKeyStream"> /// Public key stream for validating signature. /// </param> /// <param name="privateKey"> /// Private key for decrypting data. /// </param> /// <returns> /// Return true if the data is valid; false otherwise. /// </returns> private static bool ProcessDecryptionMessageBlocks( PgpPublicKeyEncryptedData encryptedData, Stream outputStream, Stream publicKeyStream, PgpPrivateKey privateKey) { var valid = true; PgpOnePassSignatureList onePassSignatureList = null; PgpOnePassSignature onePassSignature = null; PgpPublicKey publicKey = null; var clear = encryptedData.GetDataStream(privateKey); var plainFact = new PgpObjectFactory(clear); var message = plainFact.NextPgpObject(); while (message != null) { Console.WriteLine(message.ToString()); if (message is PgpCompressedData) { var compressedData = (PgpCompressedData)message; plainFact = new PgpObjectFactory(compressedData.GetDataStream()); } else if (message is PgpLiteralData) { onePassSignature = InitOnePassSignatureFromLiteral( publicKeyStream, onePassSignatureList, ref publicKey); ProcessDecryptionStreams(outputStream, message, onePassSignature); } else if (message is PgpOnePassSignatureList) { onePassSignatureList = (PgpOnePassSignatureList)message; } else if (message is PgpSignatureList) { valid = VerifyOnePassSignature(message, onePassSignature, publicKey, valid); } else { throw new PgpException("message unknown message type."); } message = plainFact.NextPgpObject(); } return(valid); }
/*.......................................................................檔案數認證開始*/ /*首先傳送端將訊息經過雜湊演算法計算後得到一個雜湊值,再利用它的私有鑰匙向雜湊值加密成為一個數位簽章(DS),接著,再將數位簽章附加在訊息後面一併傳送出去; * 接收端收到訊息之後,以同樣的雜湊演算計算出雜湊值(H’),並利用傳送端的公開鑰匙將 DS 解密,得到另一端的雜湊值(H)。 * 接著,比較兩個雜湊值,如果相同的話,則可以確定該訊息的『完整性』(雜湊值相同),此外也可以確定其『不可否認性』(私有鑰匙與公開鑰匙配對)。*/ /* * 簽章後的hash值 -> 公鑰(對方)解密 -> hash值 * 解密後的文章 -> hash -> 解密後文章的hash值 */ private static void VerifyFile( Stream inputStream, //預計數位認證原始檔案的資料流 Stream keyIn, //簽名方(對方)公鑰的資料流 string outputFileName //預計匯出(數位認證後檔案)的完整路徑 ) { inputStream = PgpUtilities.GetDecoderStream(inputStream); //串流陣列化 byte Array PgpObjectFactory pgpFact = new PgpObjectFactory(inputStream); PgpCompressedData c1 = (PgpCompressedData)pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(c1.GetDataStream()); //解壓縮 PgpOnePassSignatureList p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject(); PgpOnePassSignature ops = p1[0]; PgpLiteralData p2 = (PgpLiteralData)pgpFact.NextPgpObject(); Stream dIn = p2.GetInputStream(); PgpPublicKeyRingBundle pgpRing = new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(keyIn)); PgpPublicKey key = pgpRing.GetPublicKey(ops.KeyId); //取出公鑰 Stream fileOutput = File.Create(outputFileName); //預計匯出檔案建立 ops.InitVerify(key); //驗證公鑰是否符合 int ch; while ((ch = dIn.ReadByte()) >= 0) { ops.Update((byte)ch); //進行解密 fileOutput.WriteByte((byte)ch); //寫入預計匯出檔案 } fileOutput.Close(); fileOutput.Dispose(); PgpSignatureList p3 = (PgpSignatureList)pgpFact.NextPgpObject(); PgpSignature firstSig = p3[0]; if (ops.Verify(firstSig)) //Hash值比較 { Console.Out.WriteLine("signature verified."); } else { Console.Out.WriteLine("signature verification failed."); } }
/** * verify the passed in file as being correctly signed. */ private static void VerifyFile( Stream inputStream, Stream keyIn) { inputStream = PgpUtilities.GetDecoderStream(inputStream); PgpObjectFactory pgpFact = new PgpObjectFactory(inputStream); PgpCompressedData c1 = (PgpCompressedData)pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(c1.GetDataStream()); PgpOnePassSignatureList p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject(); PgpOnePassSignature ops = p1[0]; PgpLiteralData p2 = (PgpLiteralData)pgpFact.NextPgpObject(); Stream dIn = p2.GetInputStream(); PgpPublicKeyRingBundle pgpRing = new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(keyIn)); IPgpPublicKey key = pgpRing.GetPublicKey(ops.KeyId); Stream fos = File.Create(p2.FileName); ops.InitVerify(key); int ch; while ((ch = dIn.ReadByte()) >= 0) { ops.Update((byte)ch); fos.WriteByte((byte)ch); } fos.Close(); PgpSignatureList p3 = (PgpSignatureList)pgpFact.NextPgpObject(); PgpSignature firstSig = p3[0]; if (ops.Verify(firstSig)) { Console.Out.WriteLine("signature verified."); } else { Console.Out.WriteLine("signature verification failed."); } }
private SignatureStatus DecryptFile() { if (InStream.CanSeek) { InStream.Seek(0, SeekOrigin.Begin); } var inputStream = PgpUtilities.GetDecoderStream(InStream); try { PgpObjectFactory pgpF = new PgpObjectFactory(inputStream); PgpEncryptedDataList enc; 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(); } var privateKeys = GetAllPrivateKeys(); // // find the secret key // PgpPrivateKey sKey = null; PgpPublicKeyEncryptedData pbe = null; foreach (PgpPublicKeyEncryptedData pked in enc.GetEncryptedDataObjects()) { sKey = FindPrivateKey(privateKeys, pked.KeyId); if (sKey != null) { pbe = pked; break; } } if (sKey == null) { throw new SecretKeyNotFound("secret key for message not found."); } Stream clear = pbe.GetDataStream(sKey); PgpLiteralData pgpLiteralData = null; PgpOnePassSignatureList onePassSignatureList = null; PgpSignatureList signatureList = null; PgpObjectFactory pgpObjectFactory = new PgpObjectFactory(clear); var pgpObject = pgpObjectFactory.NextPgpObject(); while (pgpObject != null) { if (pgpObject is PgpCompressedData) { var compressedData = (PgpCompressedData)pgpObject; pgpObjectFactory = new PgpObjectFactory(compressedData.GetDataStream()); pgpObject = pgpObjectFactory.NextPgpObject(); } if (pgpObject is PgpLiteralData) { pgpLiteralData = pgpObject as PgpLiteralData; //must read directly to continue reading next pgp objects Stream unc = pgpLiteralData.GetInputStream(); Streams.PipeAll(unc, OutStream); } else if (pgpObject is PgpOnePassSignatureList) { onePassSignatureList = pgpObject as PgpOnePassSignatureList; } else if (pgpObject is PgpSignatureList) { signatureList = pgpObject as PgpSignatureList; } pgpObject = pgpObjectFactory.NextPgpObject(); } if (pgpLiteralData == null) { throw new PgpLitralDataNotFound("couldn't find pgp literal data"); } if (pbe.IsIntegrityProtected()) { if (!pbe.Verify()) { throw new PgpIntegrityCheckFailed("message failed integrity check"); } } if (CheckSignature) { if (onePassSignatureList == null || signatureList == null) { return(SignatureStatus.NoSignature); } else { return(VerifyFileSignature(OutStream, onePassSignatureList, signatureList)); } } else { return(SignatureStatus.NotChecked); } } catch { throw; } }
public override void PerformTest() { PgpPublicKey pubKey = null; // // Read the public key // PgpPublicKeyRing pgpPub = new PgpPublicKeyRing(testPubKey); pubKey = pgpPub.GetPublicKey(); // // Read the private key // PgpSecretKeyRing sKey = new PgpSecretKeyRing(testPrivKey); PgpSecretKey secretKey = sKey.GetSecretKey(); PgpPrivateKey pgpPrivKey = secretKey.ExtractPrivateKey(pass); // // test signature message // PgpObjectFactory pgpFact = new PgpObjectFactory(sig1); PgpCompressedData c1 = (PgpCompressedData)pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(c1.GetDataStream()); PgpOnePassSignatureList p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject(); PgpOnePassSignature ops = p1[0]; PgpLiteralData p2 = (PgpLiteralData)pgpFact.NextPgpObject(); Stream dIn = p2.GetInputStream(); ops.InitVerify(pubKey); int ch; while ((ch = dIn.ReadByte()) >= 0) { ops.Update((byte)ch); } PgpSignatureList p3 = (PgpSignatureList)pgpFact.NextPgpObject(); if (!ops.Verify(p3[0])) { Fail("Failed signature check"); } // // signature generation // GenerateTest(sKey, pubKey, pgpPrivKey); // // signature generation - canonical text // 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.CanonicalTextDocument, 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.Text, "_CONSOLE", dataBytes.Length, testDateTime); while ((ch = testIn.ReadByte()) >= 0) { lOut.WriteByte((byte)ch); sGen.Update((byte)ch); } lGen.Close(); sGen.Generate().Encode(bcOut); cGen.Close(); // // verify Generated signature - canconical text // pgpFact = new PgpObjectFactory(bOut.ToArray()); c1 = (PgpCompressedData)pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(c1.GetDataStream()); p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject(); ops = p1[0]; p2 = (PgpLiteralData)pgpFact.NextPgpObject(); if (!p2.ModificationTime.Equals(testDateTime)) { Fail("Modification time not preserved"); } dIn = p2.GetInputStream(); ops.InitVerify(pubKey); while ((ch = dIn.ReadByte()) >= 0) { ops.Update((byte)ch); } p3 = (PgpSignatureList)pgpFact.NextPgpObject(); if (!ops.Verify(p3[0])) { Fail("Failed generated signature check"); } // // Read the public key with user attributes // pgpPub = new PgpPublicKeyRing(testPubWithUserAttr); pubKey = pgpPub.GetPublicKey(); int count = 0; foreach (PgpUserAttributeSubpacketVector attributes in pubKey.GetUserAttributes()) { int sigCount = 0; foreach (object sigs in pubKey.GetSignaturesForUserAttribute(attributes)) { if (sigs == null) { Fail("null signature found"); } sigCount++; } if (sigCount != 1) { Fail("Failed user attributes signature check"); } count++; } if (count != 1) { Fail("Failed user attributes check"); } byte[] pgpPubBytes = pgpPub.GetEncoded(); pgpPub = new PgpPublicKeyRing(pgpPubBytes); pubKey = pgpPub.GetPublicKey(); count = 0; foreach (object ua in pubKey.GetUserAttributes()) { if (ua == null) { Fail("null user attribute found"); } count++; } if (count != 1) { Fail("Failed user attributes reread"); } // // reading test extra data - key with edge condition for DSA key password. // char[] passPhrase = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; sKey = new PgpSecretKeyRing(testPrivKey2); pgpPrivKey = sKey.GetSecretKey().ExtractPrivateKey(passPhrase); // // reading test - aes256 encrypted passphrase. // sKey = new PgpSecretKeyRing(aesSecretKey); pgpPrivKey = sKey.GetSecretKey().ExtractPrivateKey(pass); // // reading test - twofish encrypted passphrase. // sKey = new PgpSecretKeyRing(twofishSecretKey); pgpPrivKey = sKey.GetSecretKey().ExtractPrivateKey(pass); // // use of PgpKeyPair // DsaParametersGenerator pGen = new DsaParametersGenerator(); pGen.Init(512, 80, new SecureRandom()); // TODO Is the certainty okay? DsaParameters dsaParams = pGen.GenerateParameters(); DsaKeyGenerationParameters kgp = new DsaKeyGenerationParameters(new SecureRandom(), dsaParams); IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator("DSA"); kpg.Init(kgp); AsymmetricCipherKeyPair kp = kpg.GenerateKeyPair(); PgpKeyPair pgpKp = new PgpKeyPair(PublicKeyAlgorithmTag.Dsa, kp.Public, kp.Private, DateTime.UtcNow); PgpPublicKey k1 = pgpKp.PublicKey; PgpPrivateKey k2 = pgpKp.PrivateKey; }
/** * Generated signature test * * @param sKey * @param pgpPrivKey * @return test result */ public void GenerateTest( PgpSecretKeyRing sKey, PgpPublicKey pgpPubKey, PgpPrivateKey pgpPrivKey) { string data = "hello world!"; MemoryStream bOut = new MemoryStream(); byte[] dataBytes = Encoding.ASCII.GetBytes(data); MemoryStream testIn = new MemoryStream(dataBytes, false); PgpSignatureGenerator sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1); sGen.InitSign(PgpSignature.BinaryDocument, pgpPrivKey); PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator(); IEnumerator enumerator = sKey.GetSecretKey().PublicKey.GetUserIds().GetEnumerator(); enumerator.MoveNext(); string primaryUserId = (string)enumerator.Current; spGen.SetSignerUserId(true, primaryUserId); sGen.SetHashedSubpackets(spGen.Generate()); 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(); PgpObjectFactory 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(pgpPubKey); while ((ch = dIn.ReadByte()) >= 0) { ops.Update((byte)ch); } PgpSignatureList p3 = (PgpSignatureList)pgpFact.NextPgpObject(); if (!ops.Verify(p3[0])) { Fail("Failed generated signature check"); } }
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."); // } } } }
public static byte[] Decrypt(byte[] encryptedData, RetrievePgpKeys keys, AlgorithmAgreement agreed) { Stream inputStream = new MemoryStream(encryptedData); inputStream = PgpUtilities.GetDecoderStream(inputStream); PgpObjectFactory pgpObjFactory = new PgpObjectFactory(inputStream); PgpEncryptedDataList enc; PgpObject pgpObj = pgpObjFactory.NextPgpObject(); if (pgpObj is PgpEncryptedDataList) { enc = (PgpEncryptedDataList)pgpObj; } else { enc = (PgpEncryptedDataList)pgpObjFactory.NextPgpObject(); } PgpPrivateKey privKey = keys.PrivateKey; PgpPublicKeyEncryptedData pbe = null; foreach (PgpPublicKeyEncryptedData pked in enc.GetEncryptedDataObjects()) { if (privKey != null) { pbe = pked; break; } } PgpOnePassSignatureList onePassSigList = null; PgpSignatureList signatureList = null; PgpLiteralData literalData = null; byte[] returnBytes = null; Stream clear = pbe.GetDataStream(privKey); PgpObjectFactory plainFactory = new PgpObjectFactory(clear); for (; ;) { PgpObject message = plainFactory.NextPgpObject(); if (message == null) { break; } if (message is PgpCompressedData) { PgpCompressedData compressedData = (PgpCompressedData)message; plainFactory = new PgpObjectFactory(compressedData.GetDataStream()); } else if (message is PgpLiteralData) { literalData = (PgpLiteralData)message; Stream unc = literalData.GetInputStream(); returnBytes = Org.BouncyCastle.Utilities.IO.Streams.ReadAll(unc); unc.Close(); } else if (message is PgpOnePassSignatureList) { onePassSigList = (PgpOnePassSignatureList)message; } else if (message is PgpSignatureList) { signatureList = (PgpSignatureList)message; } else if (message is PgpMarker) { } else { throw new PgpException("message contains unknown message type."); } } //Stream unc = literalData.GetInputStream(); //byte[] returnBytes = Org.BouncyCastle.Utilities.IO.Streams.ReadAll(unc); if ((onePassSigList != null) && (signatureList != null)) { VerifySignature(onePassSigList, signatureList, keys.SecretKey.PublicKey, returnBytes); } //unc.Close(); clear.Close(); inputStream.Close(); return(returnBytes); }
private void doSigGenerateTest( string privateKeyFile, string publicKeyFile, HashAlgorithmTag digest) { PgpSecretKeyRing secRing = loadSecretKey(privateKeyFile); PgpPublicKeyRing pubRing = loadPublicKey(publicKeyFile); 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, digest); sGen.InitSign(PgpSignature.BinaryDocument, secRing.GetSecretKey().ExtractPrivateKey("test".ToCharArray())); BcpgOutputStream bcOut = new BcpgOutputStream(bOut); sGen.GenerateOnePassVersion(false).Encode(bcOut); PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator(); // Date testDate = new Date((System.currentTimeMillis() / 1000) * 1000); DateTime testDate = new DateTime( (DateTime.UtcNow.Ticks / TimeSpan.TicksPerSecond) * TimeSpan.TicksPerSecond); Stream lOut = lGen.Open( new UncloseableStream(bcOut), PgpLiteralData.Binary, "_CONSOLE", dataBytes.Length, testDate); int ch; while ((ch = testIn.ReadByte()) >= 0) { lOut.WriteByte((byte)ch); sGen.Update((byte)ch); } lGen.Close(); sGen.Generate().Encode(bcOut); PgpObjectFactory pgpFact = new PgpObjectFactory(bOut.ToArray()); PgpOnePassSignatureList p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject(); PgpOnePassSignature ops = p1[0]; Assert.AreEqual(digest, ops.HashAlgorithm); Assert.AreEqual(PublicKeyAlgorithmTag.Dsa, ops.KeyAlgorithm); PgpLiteralData p2 = (PgpLiteralData)pgpFact.NextPgpObject(); if (!p2.ModificationTime.Equals(testDate)) { Assert.Fail("Modification time not preserved"); } Stream dIn = p2.GetInputStream(); ops.InitVerify(pubRing.GetPublicKey()); while ((ch = dIn.ReadByte()) >= 0) { ops.Update((byte)ch); } PgpSignatureList p3 = (PgpSignatureList)pgpFact.NextPgpObject(); PgpSignature sig = p3[0]; Assert.AreEqual(digest, sig.HashAlgorithm); Assert.AreEqual(PublicKeyAlgorithmTag.Dsa, sig.KeyAlgorithm); Assert.IsTrue(ops.Verify(sig)); }
/// <summary> /// Verifies a PGP signature. See documentation at https://github.com/CommunityHiQ/Frends.Community.PgpVerifySignature Returns: Object {string FilePath, Boolean Verified} /// </summary> public static Result PGPVerifySignFile(Input input) { using (var inputStream = PgpUtilities.GetDecoderStream(File.OpenRead(input.InputFile))) using (var keyStream = PgpUtilities.GetDecoderStream(File.OpenRead(input.PublicKeyFile))) { PgpObjectFactory pgpFact = new PgpObjectFactory(inputStream); PgpOnePassSignatureList signatureList = (PgpOnePassSignatureList)pgpFact.NextPgpObject(); PgpOnePassSignature onePassSignature = signatureList[0]; PgpLiteralData p2 = (PgpLiteralData)pgpFact.NextPgpObject(); Stream dataIn = p2.GetInputStream(); PgpPublicKeyRingBundle pgpRing = new PgpPublicKeyRingBundle(keyStream); PgpPublicKey key = pgpRing.GetPublicKey(onePassSignature.KeyId); string outputPath; if (String.IsNullOrWhiteSpace(input.OutputFolder)) { outputPath = Path.Combine(Path.GetDirectoryName(input.InputFile), p2.FileName); } else { outputPath = Path.Combine(input.OutputFolder, p2.FileName); } using (var outputStream = File.Create(outputPath)) { onePassSignature.InitVerify(key); int ch; while ((ch = dataIn.ReadByte()) >= 0) { onePassSignature.Update((byte)ch); outputStream.WriteByte((byte)ch); } outputStream.Close(); } bool verified; // Will throw Exception if file is altered try { PgpSignatureList p3 = (PgpSignatureList)pgpFact.NextPgpObject(); PgpSignature firstSig = p3[0]; verified = onePassSignature.Verify(firstSig); } catch (Exception) { Result retError = new Result { FilePath = input.OutputFolder, Verified = false }; return(retError); } Result ret = new Result { FilePath = outputPath, Verified = verified }; return(ret); } }
private static Stream DecryptFileAsStream( Stream inputStream, Stream keyIn, char[] passwd) { inputStream = PgpUtilities.GetDecoderStream(inputStream); MemoryStream outputStream = new MemoryStream(); try { PgpObjectFactory pgpF = new PgpObjectFactory(inputStream); PgpEncryptedDataList enc; 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(); } // find the secret key PgpPrivateKey sKey = null; PgpPublicKeyEncryptedData pbe = null; foreach (PgpPublicKeyEncryptedData pked in enc.GetEncryptedDataObjects()) { sKey = FindSecretKey(keyIn, pked.KeyId, passwd); if (sKey != null) { pbe = pked; break; } } // Iterator it = enc.GetEncryptedDataObjects(); // // while (sKey == null && it.hasNext()) // { // pbe = (PgpPublicKeyEncryptedData)it.next(); // // sKey = FindSecretKey(keyIn, pbe.KeyID, passwd); // } 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(); if (message is PgpOnePassSignatureList) { //throw new PgpException("encrypted message contains a signed message - not literal data."); // file is signed! // verify signature here if you want. PgpOnePassSignatureList p1 = (PgpOnePassSignatureList)message; PgpOnePassSignature ops = p1[0]; // etc… message = pgpFact.NextPgpObject(); } } if (message is PgpLiteralData) { PgpLiteralData ld = (PgpLiteralData)message; Stream unc = ld.GetInputStream(); int ch; while ((ch = unc.ReadByte()) >= 0) { outputStream.WriteByte((byte)ch); } outputStream.Seek(0, SeekOrigin.Begin); } else { throw new PgpException("message is not a simple encrypted file - type unknown."); } 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"); } return(outputStream); } catch (PgpException e) { Console.Error.WriteLine(e); Exception underlyingException = e.InnerException; if (underlyingException != null) { Console.Error.WriteLine(underlyingException.Message); Console.Error.WriteLine(underlyingException.StackTrace); } throw; } }
public static byte[] Decrypt2(byte[] encryptedData, RetrievePgpKeys keys, AlgorithmAgreement agreed) { Stream inputStream = new MemoryStream(encryptedData); inputStream = PgpUtilities.GetDecoderStream(inputStream); PgpObjectFactory pgpObjFactory = new PgpObjectFactory(inputStream); PgpEncryptedDataList enc; PgpObject pgpObj = pgpObjFactory.NextPgpObject(); if (pgpObj is PgpEncryptedDataList) { enc = (PgpEncryptedDataList)pgpObj; } else { enc = (PgpEncryptedDataList)pgpObjFactory.NextPgpObject(); } PgpPrivateKey privKey = keys.PrivateKey; PgpPublicKeyEncryptedData pbe = null; foreach (PgpPublicKeyEncryptedData pked in enc.GetEncryptedDataObjects()) { if (privKey != null) { pbe = pked; break; } } PgpOnePassSignatureList onePassSigList = null; PgpSignatureList signatureList = null; PgpLiteralData literalData = null; Stream clear = pbe.GetDataStream(privKey); PgpObjectFactory plainFactory = new PgpObjectFactory(clear); PgpObject message = plainFactory.NextPgpObject(); if (message is PgpCompressedData) { PgpCompressedData compressedData = (PgpCompressedData)message; Stream compDataIn = compressedData.GetDataStream(); PgpObjectFactory objectFactory = new PgpObjectFactory(compDataIn); message = objectFactory.NextPgpObject(); if (message is PgpOnePassSignatureList) { onePassSigList = (message as PgpOnePassSignatureList); message = objectFactory.NextPgpObject(); if (message is PgpLiteralData) { literalData = (PgpLiteralData)message; } message = objectFactory.NextPgpObject(); if (message is PgpSignatureList) { signatureList = (PgpSignatureList)message; } } compDataIn.Close(); } else { if (message is PgpOnePassSignatureList) { onePassSigList = (message as PgpOnePassSignatureList); } message = plainFactory.NextPgpObject(); if (message is PgpLiteralData) { literalData = (PgpLiteralData)message; } message = plainFactory.NextPgpObject(); if (message is PgpSignatureList) { signatureList = (PgpSignatureList)message; } } Stream unc = literalData.GetInputStream(); byte[] returnBytes = Org.BouncyCastle.Utilities.IO.Streams.ReadAll(unc); if (onePassSigList != null && signatureList != null) { VerifySignature(onePassSigList, signatureList, keys.SecretKey.PublicKey, returnBytes); } unc.Close(); clear.Close(); inputStream.Close(); return(returnBytes); }