private void VerifyMessageSignature(PgpSignature sig) { if (!sig.Verify()) { throw new PgpException("The signature of the file couldn't be verified."); } }
private OpenPgpSignature Verify(ArraySegment <byte> data, PgpSignature signature) { var key = PublicBundle.GetPublicKey(signature.KeyId); if (key == null) { return(new MissingKeySignature(signature.KeyId)); } else { signature.InitVerify(key); signature.Update(data.Array, data.Offset, data.Count); if (signature.Verify()) { return(new ValidSignature(key.KeyId, key.GetFingerprint(), signature.CreationTime)); } else { var badSig = new BadSignature(signature.KeyId); Log.Warn(badSig.ToString()); return(badSig); } } }
/// <summary> /// Attempt to verify a PGP signed message using the matching public key. /// </summary> /// <param name="signedMessageStream">Stream containing the signed message.</param> /// <param name="signatureStream">Stream containing the signature.</param> /// <param name="publicKey">BouncyCastle public key to be used for verification.</param> /// <remarks>The message and signature should be passed in without ASCII Armor.</remarks> /// <returns>Whether the message's signature is verified.</returns> public static bool VerifySignature(Stream signedMessageStream, Stream signatureStream, PgpPublicKey publicKey) { // Decode from Base-64. using (Stream decoderStream = PgpUtilities.GetDecoderStream(signatureStream)) { // Extract the signature list. PgpObjectFactory pgpObjectFactory = new PgpObjectFactory(decoderStream); PgpObject pgpObject = pgpObjectFactory.NextPgpObject(); if (pgpObject is PgpSignatureList) { PgpSignatureList signatureList = pgpObject as PgpSignatureList; // Hydrate the signature object with the message to be verified. PgpSignature signature = signatureList[0]; signature.InitVerify(publicKey); signedMessageStream.Seek(0, SeekOrigin.Begin); for (int i = 0; i < signedMessageStream.Length; i++) { signature.Update((byte)signedMessageStream.ReadByte()); } // Return the result. return(signature.Verify()); } else { return(false); } } }
/** * 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()); } }
private OpenPgpSignature Verify([NotNull] byte[] data, [NotNull] PgpSignature signature) { var key = PublicBundle.GetPublicKey(signature.KeyId); if (key == null) { return(new MissingKeySignature(signature.KeyId)); } else { signature.InitVerify(key); signature.Update(data); if (signature.Verify()) { return(new ValidSignature(key.KeyId, key.GetFingerprint(), signature.CreationTime)); } else { var badSig = new BadSignature(signature.KeyId); Log.Warn(badSig.ToString()); return(badSig); } } }
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."); } }
public void ReferenceTest() { var pubKeyRing = new PgpPublicKeyRing(referencePubKey); var publicKey = pubKeyRing.GetPublicKey(); var signature = new PgpSignature(referenceSignature); Assert.IsTrue(signature.Verify(publicKey, new MemoryStream(Encoding.ASCII.GetBytes(referenceMessage), false)), "signature failed to verify!"); }
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 override void PerformTest() { // // Read the public key // PgpPublicKeyRing pubKeyRing = new PgpPublicKeyRing(testPubKey); foreach (PgpSignature certification in pubKeyRing.GetPublicKey().GetSignatures()) { certification.InitVerify(pubKeyRing.GetPublicKey()); if (!certification.VerifyCertification((string)First(pubKeyRing.GetPublicKey().GetUserIds()), pubKeyRing.GetPublicKey())) { Fail("self certification does not verify"); } } if (pubKeyRing.GetPublicKey().BitStrength != 256) { Fail("incorrect bit strength returned"); } // // Read the private key // PgpSecretKeyRing secretKeyRing = new PgpSecretKeyRing(testPrivKey); PgpPrivateKey privKey = secretKeyRing.GetSecretKey().ExtractPrivateKey(testPasswd); GenerateAndSign(); // // sExpr // byte[] msg = Encoding.ASCII.GetBytes("hello world!"); PgpSecretKey key = PgpSecretKey.ParseSecretKeyFromSExpr(new MemoryStream(sExprKey, false), "test".ToCharArray()); PgpSignatureGenerator signGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.ECDsa, HashAlgorithmTag.Sha256); signGen.InitSign(PgpSignature.BinaryDocument, key.ExtractPrivateKey(null)); signGen.Update(msg); PgpSignature sig = signGen.Generate(); sig.InitVerify(key.PublicKey); sig.Update(msg); if (!sig.Verify()) { Fail("signature failed to verify!"); } }
/** * 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> /// Verifies a PGP signature. /// </summary> /// <param name="signature"> /// The PGP signature to verify. /// </param> /// <param name="key"> /// The public key of the signer. /// </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, PgpPublicKey key, Stream payload) { signature.InitVerify(key); byte[] buffer = new byte[1024]; int read; while ((read = payload.Read(buffer, 0, buffer.Length)) > 0) { signature.Update(buffer, 0, read); } return(signature.Verify()); }
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 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()); } }
private void DoTestMasterKey() { PgpSecretKey key = PgpSecretKey.ParseSecretKeyFromSExpr(new MemoryStream(sExprKeyMaster, false), "test".ToCharArray()); byte[] msg = Encoding.UTF8.GetBytes("hello world!"); PgpSignatureGenerator signGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.ECDsa, HashAlgorithmTag.Sha256); signGen.InitSign(PgpSignature.BinaryDocument, key.ExtractPrivateKey(null)); signGen.Update(msg); PgpSignature sig = signGen.Generate(); PgpPublicKey publicKey = new PgpPublicKeyRing(testPubKey).GetPublicKey(); sig.InitVerify(publicKey); sig.Update(msg); if (!sig.Verify()) { Fail("signature failed to verify!"); } }
private static bool VerifySignature(PgpPublicKey publicKey, string payload, PgpSignature signature) { signature.InitVerify(publicKey); signature.Update(Encoding.UTF8.GetBytes(payload)); return(signature.Verify()); }
/// <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); }
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); } }
public static bool VerifySig(byte[] asc, string sig, out string message) { try { foreach (PgpPublicKey pubkey in new PgpPublicKeyRing(GetStream(asc)).GetPublicKeys().OfType <PgpPublicKey>()) //java madness { //AGAIN MADNESS THIS MAKE PERFECT SENSE ! ArmoredInputStream sigInput = new ArmoredInputStream(new MemoryStream(Encoding.UTF8.GetBytes(sig))); // // read the input, making sure we ingore the last newline. // int ch; string newLine = null; MemoryStream bOut = new MemoryStream(); while ((ch = sigInput.ReadByte()) >= 0 && sigInput.IsClearText()) { if (newLine != null) { foreach (var c in newLine) { bOut.WriteByte((byte)c); } newLine = null; } if (ch == '\r') { ch = sigInput.ReadByte(); if (ch == '\n') { newLine = "\r\n"; continue; } } if (ch == '\n') { newLine = "\n"; continue; } bOut.WriteByte((byte)ch); } var toSign = bOut.ToArray(); message = Encoding.UTF8.GetString(toSign); PgpObjectFactory pgpObjFactory = new PgpObjectFactory(sigInput); var list = (PgpSignatureList)pgpObjFactory.NextPgpObject(); PgpSignature pgpSig = list[0]; pgpSig.InitVerify(pubkey); pgpSig.Update(toSign); var result = pgpSig.Verify(); if (result) { return(result); } Regex endofline = new Regex("[ ]+?(\r?)\n"); message = endofline.Replace(message, "$1\n"); toSign = Encoding.UTF8.GetBytes(message); pgpSig.InitVerify(pubkey); pgpSig.Update(toSign); result = pgpSig.Verify(); if (result) { return(result); } } } catch //Don't do it at home kids { } message = null; return(false); }
private void GenerateAndSign() { SecureRandom random = SecureRandom.GetInstance("SHA1PRNG"); IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator("ECDSA"); keyGen.Init(new ECKeyGenerationParameters(SecObjectIdentifiers.SecP256r1, random)); AsymmetricCipherKeyPair kpSign = keyGen.GenerateKeyPair(); PgpKeyPair ecdsaKeyPair = new PgpKeyPair(PublicKeyAlgorithmTag.ECDsa, kpSign, DateTime.UtcNow); byte[] msg = Encoding.ASCII.GetBytes("hello world!"); // // try a signature // PgpSignatureGenerator signGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.ECDsa, HashAlgorithmTag.Sha256); signGen.InitSign(PgpSignature.BinaryDocument, ecdsaKeyPair.PrivateKey); signGen.Update(msg); PgpSignature sig = signGen.Generate(); sig.InitVerify(ecdsaKeyPair.PublicKey); sig.Update(msg); if (!sig.Verify()) { Fail("signature failed to verify!"); } // // generate a key ring // char[] passPhrase = "test".ToCharArray(); PgpKeyRingGenerator keyRingGen = new PgpKeyRingGenerator(PgpSignature.PositiveCertification, ecdsaKeyPair, "*****@*****.**", SymmetricKeyAlgorithmTag.Aes256, passPhrase, true, null, null, random); PgpPublicKeyRing pubRing = keyRingGen.GeneratePublicKeyRing(); PgpSecretKeyRing secRing = keyRingGen.GenerateSecretKeyRing(); PgpPublicKeyRing pubRingEnc = new PgpPublicKeyRing(pubRing.GetEncoded()); if (!Arrays.AreEqual(pubRing.GetEncoded(), pubRingEnc.GetEncoded())) { Fail("public key ring encoding failed"); } PgpSecretKeyRing secRingEnc = new PgpSecretKeyRing(secRing.GetEncoded()); if (!Arrays.AreEqual(secRing.GetEncoded(), secRingEnc.GetEncoded())) { Fail("secret key ring encoding failed"); } // // try a signature using encoded key // signGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.ECDsa, HashAlgorithmTag.Sha256); signGen.InitSign(PgpSignature.BinaryDocument, secRing.GetSecretKey().ExtractPrivateKey(passPhrase)); signGen.Update(msg); sig = signGen.Generate(); sig.InitVerify(secRing.GetSecretKey().PublicKey); sig.Update(msg); if (!sig.Verify()) { Fail("re-encoded signature failed to verify!"); } }
/* * 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."); } }