/** * verify the signature in in against the file fileName. */ private static bool VerifySignature( string OriginalMessage, string EncodedMessage, Stream keyIn) { byte[] bytes = Convert.FromBase64String(EncodedMessage); using (Stream inputStream = new MemoryStream(bytes)) { PgpObjectFactory pgpFact = new PgpObjectFactory(PgpUtilities.GetDecoderStream(inputStream)); PgpSignatureList p3 = null; PgpObject o = pgpFact.NextPgpObject(); if (o is PgpCompressedData) { PgpCompressedData c1 = (PgpCompressedData)o; pgpFact = new PgpObjectFactory(c1.GetDataStream()); p3 = (PgpSignatureList)pgpFact.NextPgpObject(); } else { p3 = (PgpSignatureList)o; } PgpPublicKeyRingBundle pgpPubRingCollection = new PgpPublicKeyRingBundle( PgpUtilities.GetDecoderStream(keyIn)); PgpSignature sig = p3[0]; PgpPublicKey key = pgpPubRingCollection.GetPublicKey(sig.KeyId); sig.InitVerify(key); sig.Update(System.Text.Encoding.UTF8.GetBytes(OriginalMessage)); return(sig.Verify()); } }
/// <summary> /// Return the public encryption key with ID "keyId". /// </summary> /// <param name="publicKeyRingStream">The key ring, in bytes</param> /// <param name="keyId">Sought key's ID</param> /// <param name="throwException">Whether to throw an exception if key does not exist, or is not an encryption key</param> /// <returns>Key, or null if exception throwing is disabled and key either can't be found, or can't encrypt.</returns> private static PgpPublicKey GetPublicEncryptionKey(Stream publicKeyRingStream, long keyId, bool throwException = true) { var keyRing = new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(publicKeyRingStream)); var key = keyRing.GetPublicKey(keyId); if (key == null) { if (throwException) { throw new ArgumentException(String.Format("Key {0:X} does not exist in key ring", keyId), "keyId"); } return(null); } if (key.IsEncryptionKey == false) { if (throwException) { throw new ArgumentException(String.Format("Key {0:X} is not an Encryption Key", keyId), "keyId"); } return(null); } return(key); }
/// <summary> /// Verifies a PGP signature. /// </summary> /// <param name="signature"> /// The PGP signature to verify. /// </param> /// <param name="publicKey"> /// A <see cref="Stream"/> which contains the PGP public key. /// </param> /// <param name="payload"> /// The payload for which the signature was generated. /// </param> /// <returns> /// <see langword="true"/> if the signature is valid; otherwise, <see langword="false"/>. /// </returns> public static bool VerifySignature(PgpSignature signature, Stream publicKey, Stream payload) { PgpPublicKeyRingBundle keyRing = new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(publicKey)); PgpPublicKey key = keyRing.GetPublicKey(signature.KeyId); return(VerifySignature(signature, key, payload)); }
/// <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); }
private static PgpPublicKey ParsePgpPublicKey(string publicKey, long keyId) { var input = PgpUtilities.GetDecoderStream(new MemoryStream(Encoding.UTF8.GetBytes(publicKey))); var pgpRings = new PgpPublicKeyRingBundle(input); return(pgpRings.GetPublicKey(keyId)); }
/// <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(); } }
/// <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); } }
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); } }
public static PgpPublicKey FindPublicKeyByKeyId(PgpPublicKeyRingBundle pgpPub, long keyId) { var pgpPubKey = pgpPub.GetPublicKey(keyId); if (pgpPubKey == null) { return(null); } return(pgpPubKey); }
/** * verify the signature in in against the file fileName. */ private static void VerifySignature( string fileName, Stream inputStream, Stream keyIn) { inputStream = PgpUtilities.GetDecoderStream(inputStream); PgpObjectFactory pgpFact = new PgpObjectFactory(inputStream); PgpSignatureList p3 = null; PgpObject o = pgpFact.NextPgpObject(); if (o is PgpCompressedData) { PgpCompressedData c1 = (PgpCompressedData)o; pgpFact = new PgpObjectFactory(c1.GetDataStream()); p3 = (PgpSignatureList)pgpFact.NextPgpObject(); } else { p3 = (PgpSignatureList)o; } PgpPublicKeyRingBundle pgpPubRingCollection = new PgpPublicKeyRingBundle( PgpUtilities.GetDecoderStream(keyIn)); Stream dIn = File.OpenRead(fileName); PgpSignature sig = p3[0]; PgpPublicKey key = pgpPubRingCollection.GetPublicKey(sig.KeyId); sig.InitVerify(key); int ch; while ((ch = dIn.ReadByte()) >= 0) { sig.Update((byte)ch); } dIn.Close(); if (sig.Verify()) { Console.WriteLine("signature verified."); } else { Console.WriteLine("signature verification failed."); } }
/// <summary> /// private method to get the public key value. /// </summary> /// <param name="_pubKeyPath">string representing the public key path</param> /// <returns>a PGPPublicKey</returns> private PgpPublicKey getPublicKey(string _pubKeyPath) { PgpPublicKey pubKey; using (Stream keyin = File.OpenRead(_pubKeyPath)) using (Stream s = PgpUtilities.GetDecoderStream(keyin)) { PgpPublicKeyRingBundle pubKeyBundle = new PgpPublicKeyRingBundle(s); pubKey = pubKeyBundle.GetPublicKey(_keyID); if (pubKey == null) { throw new Exception("The public key value is null!"); } } return(pubKey); }
private static void Main() { if (!File.Exists("MANIFEST.json.asc")) { return; } Stream inputStream = File.OpenRead("MANIFEST.json.asc"); Stream keyIn = File.OpenRead("gpg"); // https://github.com/bcgit/bc-csharp/blob/master/crypto/test/src/openpgp/examples/DetachedSignatureProcessor.cs inputStream = PgpUtilities.GetDecoderStream(inputStream); PgpObjectFactory pgpFact = new PgpObjectFactory(inputStream); PgpSignatureList p3; PgpObject o = pgpFact.NextPgpObject(); if (o is PgpCompressedData c1) { pgpFact = new PgpObjectFactory(c1.GetDataStream()); p3 = (PgpSignatureList)pgpFact.NextPgpObject(); } else { p3 = (PgpSignatureList)o; } PgpPublicKeyRingBundle pgpPubRingCollection = new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(keyIn)); Stream dIn = File.OpenRead("MANIFEST.json"); PgpSignature sig = p3[0]; PgpPublicKey key = pgpPubRingCollection.GetPublicKey(sig.KeyId); sig.InitVerify(key); int ch; while ((ch = dIn.ReadByte()) >= 0) { sig.Update((byte)ch); } dIn.Close(); Console.WriteLine(sig.Verify() ? "signature verified." : "signature verification failed."); }
public static PgpPublicKey[] FindPublicKeyByKeyId(PgpPublicKeyRingBundle pgpPub, string[] keyIDs) { var pubKeyList = new PgpPublicKey[50]; var index = 0; foreach (var pubKeyId in keyIDs) { var pgpPubKey = pgpPub.GetPublicKey(System.Convert.ToInt64(pubKeyId, 16)); if (pgpPubKey != null) { pubKeyList[index] = pgpPubKey; index++; } } return(pubKeyList); }
public static PgpPublicKey[] FindPublicKeyByKeyId(PgpPublicKeyRingBundle pgpPub, long[] keyIDs) { var pubKeyList = new PgpPublicKey[50]; var index = 0; foreach (var pubKeyId in keyIDs) { var pgpPubKey = pgpPub.GetPublicKey(pubKeyId); if (pgpPubKey != null) { pubKeyList[index] = pgpPubKey; index++; } } return(pubKeyList); }
public void MessageTest(string type, string message) { /*ArmoredInputStream aIn = new ArmoredInputStream( * new MemoryStream(Encoding.ASCII.GetBytes(message))); * * string[] headers = aIn.GetArmorHeaders(); * * Assert.NotNull(headers); * Assert.AreEqual(1, headers.Length); * * // * // read the input, making sure we ingore the last newline. * // * MemoryStream bOut = new MemoryStream(); * int ch; * * while ((ch = aIn.ReadByte()) >= 0 && aIn.IsClearText()) * { * bOut.WriteByte((byte)ch); * } * * PgpPublicKeyRingBundle pgpRings = new PgpPublicKeyRingBundle(publicKey); * * PgpSignature sig = new PgpSignature(aIn); * * // FIXME: This belongs directly to the armor reader * byte[] clearText = bOut.ToArray(); * int clearTextLength = clearText.Length; * if (clearTextLength > 0 && clearText[clearTextLength - 1] == '\n') * clearTextLength--; * if (clearTextLength > 0 && clearText[clearTextLength - 1] == '\r') * clearTextLength--; * * bool verified = sig.Verify(pgpRings.GetPublicKey(sig.KeyId), new MemoryStream(clearText, 0, clearTextLength, false), ignoreTrailingWhitespace: true); * Assert.IsTrue(verified, "signature failed to verify m_in " + type);*/ PgpPublicKeyRingBundle pgpRings = new PgpPublicKeyRingBundle(publicKey); var reader = new ArmoredPacketReader(new MemoryStream(Encoding.ASCII.GetBytes(message))); var signedMessage = (PgpSignedMessage)PgpMessage.ReadMessage(reader); var literalMessage = (PgpLiteralMessage)signedMessage.ReadMessage(); var bytes = Streams.ReadAll(literalMessage.GetStream()); Assert.IsTrue(signedMessage.Verify(pgpRings.GetPublicKey(signedMessage.KeyId))); reader.VerifyCrc(); }
/// <summary> /// Verify the signature against the file. /// </summary> /// <param name="fileName"> /// File to validate /// </param> /// <param name="signatureStream"> /// Signature to validate. /// </param> /// <param name="keyStream"> /// Public key to use for signature validation. /// </param> /// <returns> /// The <see cref="bool"/> flag indicating verification success; false means /// the signature is invalid. /// </returns> public static bool VerifyDetachedFileSignature(string fileName, Stream signatureStream, Stream keyStream) { signatureStream = PgpUtilities.GetDecoderStream(signatureStream); var objectFactory = new PgpObjectFactory(signatureStream); PgpSignatureList signatureList; var @object = objectFactory.NextPgpObject(); if (@object is PgpCompressedData) { var compressedData = (PgpCompressedData)@object; objectFactory = new PgpObjectFactory(compressedData.GetDataStream()); signatureList = (PgpSignatureList)objectFactory.NextPgpObject(); } else { signatureList = (PgpSignatureList)@object; } var pgpPubRingCollection = new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(keyStream)); var signature = signatureList[0]; var key = pgpPubRingCollection.GetPublicKey(signature.KeyId); signature.InitVerify(key); using (var fileDataStream = File.OpenRead(fileName)) { int read; var buffer = new byte[PgpCommon.BufferSize]; while ((read = fileDataStream.Read(buffer, 0, buffer.Length)) > 0) { signature.Update(buffer, 0, read); } } if (!signature.Verify()) { Console.WriteLine("signature verification failed."); return(false); } Console.WriteLine("signature verified."); return(true); }
/*.......................................................................檔案數認證開始*/ /*首先傳送端將訊息經過雜湊演算法計算後得到一個雜湊值,再利用它的私有鑰匙向雜湊值加密成為一個數位簽章(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."); } }
public static bool VerifyDetachedSignature(string filePath, Stream signatureStream, Stream publicKeyStream) { signatureStream = PgpUtilities.GetDecoderStream(signatureStream); PgpObjectFactory pgpFactory = new PgpObjectFactory(signatureStream); PgpObject pgpObject = pgpFactory.NextPgpObject(); PgpSignatureList signatureList; if (pgpObject is PgpCompressedData pgpCompressedData) { PgpCompressedData compressedData = pgpCompressedData; pgpFactory = new PgpObjectFactory(compressedData.GetDataStream()); signatureList = (PgpSignatureList)pgpFactory.NextPgpObject(); } else { signatureList = (PgpSignatureList)pgpObject; } PgpPublicKeyRingBundle keyRingBundle = new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(publicKeyStream)); using (Stream inputFileStream = File.OpenRead(filePath)) { PgpSignature signature = signatureList[0]; PgpPublicKey publicKey = keyRingBundle.GetPublicKey(signature.KeyId); signature.InitVerify(publicKey); int ch; while ((ch = inputFileStream.ReadByte()) >= 0) { signature.Update((byte)ch); } return(signature.Verify()); } }
/* * verify a clear text signed file */ public static PgpSignatureInfo VerifyFile( Stream inputStream, Stream pubkeyRing) { var aIn = new ArmoredInputStream(inputStream); Stream outStr = new MemoryStream(); // // write out signed section using the local line separator. // note: trailing white space needs to be removed from the end of // each line RFC 4880 Section 7.1 // var lineOut = new MemoryStream(); var lookAhead = ReadInputLine(lineOut, aIn); var newline = Encoding.ASCII.GetBytes(Environment.NewLine); if (lookAhead != -1 && aIn.IsClearText()) { var line = lineOut.ToArray(); outStr.Write(line, 0, GetLengthWithoutSeparatorOrTrailingWhitespace(line)); outStr.Write(newline, 0, newline.Length); while (lookAhead != -1 && aIn.IsClearText()) { lookAhead = ReadInputLine(lineOut, lookAhead, aIn); line = lineOut.ToArray(); outStr.Write(line, 0, GetLengthWithoutSeparatorOrTrailingWhitespace(line)); outStr.Write(newline, 0, newline.Length); } } //outStr.Close(); var pgpRings = new PgpPublicKeyRingBundle(pubkeyRing); var pgpFact = new PgpObjectFactory(aIn); var p3 = (PgpSignatureList)pgpFact.NextPgpObject(); var sig = p3[0]; sig.InitVerify(pgpRings.GetPublicKey(sig.KeyId)); // // read the input, making sure we ignore the last newline. // var sigIn = outStr; // Set position of stream to start. sigIn.Position = 0; lookAhead = ReadInputLine(lineOut, sigIn); ProcessLine(sig, lineOut.ToArray()); if (lookAhead != -1) { do { lookAhead = ReadInputLine(lineOut, lookAhead, sigIn); sig.Update((byte)'\r'); sig.Update((byte)'\n'); ProcessLine(sig, lineOut.ToArray()); }while (lookAhead != -1); } var siginfo = new PgpSignatureInfo(); if (sig.Verify()) { siginfo.KeyId = String.Format("{0:X}", sig.KeyId); siginfo.Valid = true; siginfo.Version = sig.Version; siginfo.Created = sig.CreationTime; siginfo.HashAlgorithm = sig.HashAlgorithm; siginfo.Signature = sig; return(siginfo); } siginfo.KeyId = String.Format("{0:X}", sig.KeyId); siginfo.Valid = false; siginfo.Version = sig.Version; siginfo.Created = sig.CreationTime; siginfo.HashAlgorithm = sig.HashAlgorithm; siginfo.Signature = sig; return(siginfo); }
/** * verify the signature in in against the file fileName. */ public static PgpSignatureInfo VerifySignature( string fileName, Stream signature, Stream keyIn) { signature = PgpUtilities.GetDecoderStream(signature); var pgpFact = new PgpObjectFactory(signature); PgpSignatureList p3; var o = pgpFact.NextPgpObject(); var data = o as PgpCompressedData; if (data != null) { var c1 = data; pgpFact = new PgpObjectFactory(c1.GetDataStream()); p3 = (PgpSignatureList)pgpFact.NextPgpObject(); } else { p3 = (PgpSignatureList)o; } var pgpPubRingCollection = new PgpPublicKeyRingBundle( PgpUtilities.GetDecoderStream(keyIn)); Stream dIn = File.OpenRead(fileName); var sig = p3[0]; var key = pgpPubRingCollection.GetPublicKey(sig.KeyId); sig.InitVerify(key); int ch; while ((ch = dIn.ReadByte()) >= 0) { sig.Update((byte)ch); } dIn.Close(); var siginfo = new PgpSignatureInfo(); if (sig.Verify()) { siginfo.KeyId = String.Format("{0:X}", sig.KeyId); siginfo.Valid = true; siginfo.Version = sig.Version; siginfo.Created = sig.CreationTime; siginfo.HashAlgorithm = sig.HashAlgorithm; siginfo.Signature = sig; return(siginfo); } siginfo.KeyId = String.Format("{0:X}", sig.KeyId); siginfo.Valid = false; siginfo.Version = sig.Version; siginfo.Created = sig.CreationTime; siginfo.HashAlgorithm = sig.HashAlgorithm; siginfo.Signature = sig; return(siginfo); }
private void messageTest( string message, string type) { ArmoredInputStream aIn = new ArmoredInputStream( new MemoryStream(Encoding.ASCII.GetBytes(message))); string[] headers = aIn.GetArmorHeaders(); if (headers == null || headers.Length != 1) { Fail("wrong number of headers found"); } if (!"Hash: SHA256".Equals(headers[0])) { Fail("header value wrong: " + headers[0]); } // // read the input, making sure we ingore the last newline. // MemoryStream bOut = new MemoryStream(); int ch; while ((ch = aIn.ReadByte()) >= 0 && aIn.IsClearText()) { bOut.WriteByte((byte)ch); } PgpPublicKeyRingBundle pgpRings = new PgpPublicKeyRingBundle(publicKey); PgpObjectFactory pgpFact = new PgpObjectFactory(aIn); PgpSignatureList p3 = (PgpSignatureList)pgpFact.NextPgpObject(); PgpSignature sig = p3[0]; sig.InitVerify(pgpRings.GetPublicKey(sig.KeyId)); MemoryStream lineOut = new MemoryStream(); Stream sigIn = new MemoryStream(bOut.ToArray(), false); int lookAhead = ReadInputLine(lineOut, sigIn); ProcessLine(sig, lineOut.ToArray()); if (lookAhead != -1) { do { lookAhead = ReadInputLine(lineOut, lookAhead, sigIn); sig.Update((byte)'\r'); sig.Update((byte)'\n'); ProcessLine(sig, lineOut.ToArray()); }while (lookAhead != -1); } if (!sig.Verify()) { Fail("signature failed to verify m_in " + type); } }
private void messageTest( string message, string type) { ArmoredInputStream aIn = new ArmoredInputStream( new MemoryStream(Encoding.ASCII.GetBytes(message))); string[] headers = aIn.GetArmorHeaders(); if (headers == null || headers.Length != 1) { Fail("wrong number of headers found"); } if (!"Hash: SHA256".Equals(headers[0])) { Fail("header value wrong: " + headers[0]); } // // read the input, making sure we ingore the last newline. // MemoryStream bOut = new MemoryStream(); int ch; while ((ch = aIn.ReadByte()) >= 0 && aIn.IsClearText()) { bOut.WriteByte((byte)ch); } PgpPublicKeyRingBundle pgpRings = new PgpPublicKeyRingBundle(publicKey); PgpObjectFactory pgpFact = new PgpObjectFactory(aIn); PgpSignatureList p3 = (PgpSignatureList)pgpFact.NextPgpObject(); PgpSignature sig = p3[0]; sig.InitVerify(pgpRings.GetPublicKey(sig.KeyId)); MemoryStream lineOut = new MemoryStream(); Stream sigIn = new MemoryStream(bOut.ToArray(), false); int lookAhead = ReadInputLine(lineOut, sigIn); ProcessLine(sig, lineOut.ToArray()); if (lookAhead != -1) { do { lookAhead = ReadInputLine(lineOut, lookAhead, sigIn); sig.Update((byte) '\r'); sig.Update((byte) '\n'); ProcessLine(sig, lineOut.ToArray()); } while (lookAhead != -1); } if (!sig.Verify()) { Fail("signature failed to verify m_in " + type); } }
/* * decrypt a given stream. */ public static void Decrypt(Stream inputStream, Stream privateKeyStream, string passPhrase, string outputFile, Stream publicKeyStream) { try { bool deleteOutputFile = false; PgpEncryptedDataList enc; PgpObject o = null; PgpPrivateKey sKey = null; PgpPublicKeyEncryptedData pbe = null; var pgpF = new PgpObjectFactory(PgpUtilities.GetDecoderStream(inputStream)); // find secret key var 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) { PgpOnePassSignature ops = ((PgpOnePassSignatureList)message)[0]; PgpPublicKeyRingBundle pgpRing = new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(publicKeyStream)); //USE THE BELOW TO CHECK FOR A FAILING SIGNATURE VERIFICATION. //THE CERTIFICATE MATCHING THE KEY ID MUST BE IN THE PUBLIC KEY RING. //long fakeKeyId = 3008998260528343108L; //PgpPublicKey key = pgpRing.GetPublicKey(fakeKeyId); PgpPublicKey key = pgpRing.GetPublicKey(ops.KeyId); ops.InitVerify(key); message = of.NextPgpObject(); PgpLiteralData Ld = null; Ld = (PgpLiteralData)message; //THE OUTPUT FILENAME WILL BE BASED ON THE INPUT PARAMETER VALUE TO THIS METHOD. IF YOU WANT TO KEEP THE //ORIGINAL FILENAME, UNCOMMENT THE FOLLOWING LINE. //if (!String.IsNullOrEmpty(Ld.FileName)) // outputFile = Ld.FileName; using (Stream output = File.Create(outputFile)) { Stream dIn = Ld.GetInputStream(); int ch; while ((ch = dIn.ReadByte()) >= 0) { ops.Update((byte)ch); output.WriteByte((byte)ch); } output.Close(); } PgpSignatureList p3 = (PgpSignatureList)of.NextPgpObject(); PgpSignature firstSig = p3[0]; if (ops.Verify(firstSig)) { Console.Out.WriteLine("signature verified."); } else { Console.Out.WriteLine("signature verification failed."); //YOU MAY OPT TO DELETE THE OUTPUT FILE IN THE EVENT THAT VERIFICATION FAILS. //FILE DELETION HAPPENS FURTHER DOWN IN THIS METHOD //AN ALTERNATIVE IS TO LOG THESE VERIFICATION FAILURE MESSAGES, BUT KEEP THE OUTPUT FILE FOR FURTHER ANALYSIS //deleteOutputFile = true; } } 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(outFileName)) { 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"); //YOU MAY OPT TO DELETE THE OUTPUT FILE IN THE EVENT THAT THE INTEGRITY PROTECTION CHECK FAILS. //FILE DELETION HAPPENS FURTHER DOWN IN THIS METHOD. //AN ALTERNATIVE IS TO LOG THESE VERIFICATION FAILURE MESSAGES, BUT KEEP THE OUTPUT FILE FOR FURTHER ANALYSIS //deleteOutputFile = true; } 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"); } if (deleteOutputFile) { File.Delete(outputFile); } #endregion commented code } catch (PgpException ex) { throw; } }
/* * verify a clear text signed file */ private static void VerifyFile( Stream inputStream, Stream keyIn, string resultName) { ArmoredInputStream aIn = new ArmoredInputStream(inputStream); Stream outStr = File.Create(resultName); // // write out signed section using the local line separator. // note: trailing white space needs to be removed from the end of // each line RFC 4880 Section 7.1 // MemoryStream lineOut = new MemoryStream(); int lookAhead = ReadInputLine(lineOut, aIn); byte[] lineSep = LineSeparator; if (lookAhead != -1 && aIn.IsClearText()) { byte[] line = lineOut.ToArray(); outStr.Write(line, 0, GetLengthWithoutSeparatorOrTrailingWhitespace(line)); outStr.Write(lineSep, 0, lineSep.Length); while (lookAhead != -1 && aIn.IsClearText()) { lookAhead = ReadInputLine(lineOut, lookAhead, aIn); line = lineOut.ToArray(); outStr.Write(line, 0, GetLengthWithoutSeparatorOrTrailingWhitespace(line)); outStr.Write(lineSep, 0, lineSep.Length); } } else { // a single line file if (lookAhead != -1) { byte[] line = lineOut.ToArray(); outStr.Write(line, 0, GetLengthWithoutSeparatorOrTrailingWhitespace(line)); outStr.Write(lineSep, 0, lineSep.Length); } } outStr.Close(); PgpPublicKeyRingBundle pgpRings = new PgpPublicKeyRingBundle(keyIn); PgpObjectFactory pgpFact = new PgpObjectFactory(aIn); PgpSignatureList p3 = (PgpSignatureList)pgpFact.NextPgpObject(); PgpSignature sig = p3[0]; sig.InitVerify(pgpRings.GetPublicKey(sig.KeyId)); // // read the input, making sure we ignore the last newline. // Stream sigIn = File.OpenRead(resultName); lookAhead = ReadInputLine(lineOut, sigIn); ProcessLine(sig, lineOut.ToArray()); if (lookAhead != -1) { do { lookAhead = ReadInputLine(lineOut, lookAhead, sigIn); sig.Update((byte)'\r'); sig.Update((byte)'\n'); ProcessLine(sig, lineOut.ToArray()); }while (lookAhead != -1); } sigIn.Close(); if (sig.Verify()) { Console.WriteLine("signature verified."); } else { Console.WriteLine("signature verification failed."); } }
public static bool ReadAndVerifyFile(Stream inputStream, Stream keyIn, out Stream cleartextOut) { // Count any exception as BouncyCastle failing to parse something, because of corruption maybe? try { // Disposing this will close the underlying stream, which we don't want to do var armouredInputStream = new ArmoredInputStream(inputStream); // This stream is returned, so is not disposed var cleartextStream = new MemoryStream(); int chr; while ((chr = armouredInputStream.ReadByte()) >= 0 && armouredInputStream.IsClearText()) { cleartextStream.WriteByte((byte)chr); } // Strip the trailing newline if set... cleartextStream.Position = Math.Max(0, cleartextStream.Position - 2); int count = 0; if (cleartextStream.ReadByte() == '\r') { count++; } if (cleartextStream.ReadByte() == '\n') { count++; } cleartextStream.SetLength(cleartextStream.Length - count); cleartextStream.Position = 0; // This will either return inputStream, or a new ArmouredStream(inputStream) // Either way, disposing it will close the underlying stream, which we don't want to do var decoderStream = PgpUtilities.GetDecoderStream(inputStream); var pgpObjectFactory = new PgpObjectFactory(decoderStream); var signatureList = (PgpSignatureList)pgpObjectFactory.NextPgpObject(); var signature = signatureList[0]; var publicKeyRing = new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(keyIn)); var publicKey = publicKeyRing.GetPublicKey(signature.KeyId); signature.InitVerify(publicKey); while ((chr = cleartextStream.ReadByte()) > 0) { signature.Update((byte)chr); } cleartextStream.Position = 0; cleartextOut = cleartextStream; return(signature.Verify()); } catch { cleartextOut = null; return(false); } }
/// <summary> /// Verifies a PGP signature. See documentation at https://github.com/CommunityHiQ/Frends.Community.PgpVerifySignature Returns: Object {string FilePath, Boolean Verified} /// </summary> public static PgpVerifySignatureResult VerifyFileSignature(PgpVerifySignatureInput input) { using (var inputStream = PgpUtilities.GetDecoderStream(File.OpenRead(input.InputFile))) using (var keyStream = PgpUtilities.GetDecoderStream(File.OpenRead(input.PublicKeyFile))) { var pgpFact = new PgpObjectFactory(inputStream); var signatureList = (PgpOnePassSignatureList)pgpFact.NextPgpObject(); if (signatureList == null) { throw new Exception("Can't find signature in file."); } var onePassSignature = signatureList[0]; var p2 = (PgpLiteralData)pgpFact.NextPgpObject(); var dataIn = p2.GetInputStream(); var pgpRing = new PgpPublicKeyRingBundle(keyStream); var key = pgpRing.GetPublicKey(onePassSignature.KeyId); string outputPath; if (string.IsNullOrWhiteSpace(input.OutputFolder)) { outputPath = Path.Combine(Path.GetDirectoryName(input.InputFile) ?? throw new ArgumentNullException(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 { var p3 = (PgpSignatureList)pgpFact.NextPgpObject(); var firstSig = p3[0]; verified = onePassSignature.Verify(firstSig); } catch (Exception) { var retError = new PgpVerifySignatureResult { FilePath = input.OutputFolder, Verified = false }; return(retError); } var ret = new PgpVerifySignatureResult { FilePath = outputPath, Verified = verified }; return(ret); } }
/// <summary> /// Verifies clear text PGP signature. See documentation at https://github.com/CommunityHiQ/Frends.Community.PgpVerifyClearTextSignature Returns: Object {string FilePath, Boolean Verified} /// </summary> public static Result PGPVerifyClearTextSignFile(Input input) { Stream inStr = File.OpenRead(input.InputFile); ArmoredInputStream aIn = new ArmoredInputStream(inStr); Stream outStr = File.Create(input.OutputFile); // // write out signed section using the local line separator. // note: trailing white space needs to be removed from the end of // each line RFC 4880 Section 7.1 // MemoryStream lineOut = new MemoryStream(); int lookAhead = ReadInputLine(lineOut, aIn); byte[] lineSep = Encoding.ASCII.GetBytes(Environment.NewLine);; if (lookAhead != -1 && aIn.IsClearText()) { byte[] line = lineOut.ToArray(); outStr.Write(line, 0, GetLengthWithoutSeparatorOrTrailingWhitespace(line)); outStr.Write(lineSep, 0, lineSep.Length); while (lookAhead != -1 && aIn.IsClearText()) { lookAhead = ReadInputLine(lineOut, lookAhead, aIn); line = lineOut.ToArray(); outStr.Write(line, 0, GetLengthWithoutSeparatorOrTrailingWhitespace(line)); outStr.Write(lineSep, 0, lineSep.Length); } } else { // a single line file if (lookAhead != -1) { byte[] line = lineOut.ToArray(); outStr.Write(line, 0, GetLengthWithoutSeparatorOrTrailingWhitespace(line)); outStr.Write(lineSep, 0, lineSep.Length); } } outStr.Close(); PgpPublicKeyRingBundle pgpRings = new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(File.OpenRead(input.PublicKeyFile))); PgpObjectFactory pgpFact = new PgpObjectFactory(aIn); PgpSignatureList p3 = (PgpSignatureList)pgpFact.NextPgpObject(); PgpSignature sig = p3[0]; inStr.Close(); sig.InitVerify(pgpRings.GetPublicKey(sig.KeyId)); // read the input, making sure we ignore the last newline. Stream sigIn = File.OpenRead(input.OutputFile); lookAhead = ReadInputLine(lineOut, sigIn); ProcessLine(sig, lineOut.ToArray()); if (lookAhead != -1) { do { lookAhead = ReadInputLine(lineOut, lookAhead, sigIn); sig.Update((byte)'\r'); sig.Update((byte)'\n'); ProcessLine(sig, lineOut.ToArray()); }while (lookAhead != -1); } bool verified = sig.Verify(); sigIn.Close(); Result ret = new Result { FilePath = input.OutputFile, Verified = verified }; return(ret); }