public string[] GetPublicKeyUserIdsForSign() { using (var inputStream = File.OpenRead(Context.PublicKeyRingFile)) { using (var decoderStream = PgpUtilities.GetDecoderStream(inputStream)) { var pgpPub = new PgpPublicKeyRingBundle(decoderStream); var keyUserIds = new List <string>(); foreach (PgpPublicKeyRing kRing in pgpPub.GetKeyRings()) { foreach (PgpPublicKey k in kRing.GetPublicKeys()) { if (!IsSigningKey(k)) { continue; } foreach (string id in k.GetUserIds()) { keyUserIds.Add(id); } } } return(keyUserIds.ToArray()); } } }
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)); }
private PgpPublicKey getFirstPublicKey(PgpPublicKeyRingBundle publicKeyRingBundle) { foreach (PgpPublicKeyRing kRing in publicKeyRingBundle.GetKeyRings()) { /* * PgpPublicKey key = kRing.GetPublicKeys() * .Cast<PgpPublicKey>() * .Where(k => k.IsEncryptionKey) * .FirstOrDefault(); * * if (key != null) * { * return key; * } */ IEnumerator ikeys = kRing.GetPublicKeys().GetEnumerator(); if (ikeys.MoveNext()) { PgpPublicKey key = (PgpPublicKey)ikeys.Current; if (key.IsEncryptionKey) { return(key); } } } return(null); }
public static bool IsPublicKey(string key) { bool isValid = false; try { byte[] byteArray = Encoding.ASCII.GetBytes(key); using (MemoryStream stream = new MemoryStream(byteArray)) { using (Stream decoderStream = PgpUtilities.GetDecoderStream(stream)) { PgpPublicKeyRingBundle publicKeyBundle = new PgpPublicKeyRingBundle(decoderStream); PgpPublicKey foundKey = GetFirstPublicKey(publicKeyBundle); if (foundKey != null) { isValid = true; } } } } catch (Exception) { isValid = false; } return(isValid); }
private static PgpPublicKey ReadPublicKey(Stream inputStream) { inputStream = PgpUtilities.GetDecoderStream(inputStream); PgpPublicKeyRingBundle pgpPub = new PgpPublicKeyRingBundle(inputStream); // // we just loop through the collection till we find a key suitable for encryption, in the real // world you would probably want to be a bit smarter about this. // // // iterate through the key rings. // foreach (PgpPublicKeyRing kRing in pgpPub.GetKeyRings()) { foreach (PgpPublicKey k in kRing.GetPublicKeys()) { if (k.IsEncryptionKey) { return(k); } } } throw new ArgumentException("Can't find encryption key in key ring."); }
public static IEnumerable <PgpPublicKeyMetaData> GetPublicKeys(Stream inputStream) //, bool disallowPrivateKeys) { inputStream = PgpUtilities.GetDecoderStream(inputStream); //if (disallowPrivateKeys) //{ // PgpSecretKeyRingBundle pgpKeyRing = null; // try // { // pgpKeyRing = new PgpSecretKeyRingBundle(inputStream); // } // catch // { // } // if (pgpKeyRing != null && pgpKeyRing.Count > 0) // { // throw new System.Security.SecurityException("Private keys are not allowed."); // } //} var list = new List <PgpPublicKeyMetaData>(); PgpPublicKeyRingBundle pgpPub = new PgpPublicKeyRingBundle(inputStream); foreach (PgpPublicKeyRing keyRing in pgpPub.GetKeyRings()) { foreach (PgpPublicKey key in keyRing.GetPublicKeys()) { var keyMeta = new PgpPublicKeyMetaData(); keyMeta.Load(key); list.Add(keyMeta); } } return(list); }
/// <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); }
/** * 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); }
private PgpPublicKey GetPublicKeyByUserId(PgpPublicKeyRingBundle publicKeyRingBundle, String publicKeyUserId) { foreach (PgpPublicKeyRing kRing in publicKeyRingBundle.GetKeyRings()) { PgpPublicKey key = kRing.GetPublicKeys() .Cast <PgpPublicKey>() .Where(k => k.IsEncryptionKey) .FirstOrDefault(); if (key != null) { foreach (String userId in key.GetUserIds()) { if (userId.Contains(publicKeyUserId)) { return(key); } } } } return(null); }
private static PgpPublicKey ReadPublicKey(Stream publicKeyStream) { if (publicKeyStream.CanSeek) { publicKeyStream.Seek(0, SeekOrigin.Begin); } PgpPublicKeyRingBundle pgpPub = new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(publicKeyStream)); // // we just loop through the collection till we find a key suitable for encryption, in the real // world you would probably want to be a bit smarter about this. // foreach (PgpPublicKeyRing keyRing in pgpPub.GetKeyRings()) { foreach (PgpPublicKey key in keyRing.GetPublicKeys()) { if (key.IsEncryptionKey) { return(key); } } } throw new ArgumentException("Can't find encryption key in key ring."); }
/// <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> /// Export the public keyring bundle. /// </summary> /// <remarks> /// Exports the public keyring bundle. /// </remarks> /// <param name="keys">The public keyring bundle to export.</param> /// <param name="stream">The output stream.</param> /// <param name="armor"><c>true</c> if the output should be armored; otherwise, <c>false</c>.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="keys"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="stream"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.IO.IOException"> /// An I/O error occurred. /// </exception> public void Export(PgpPublicKeyRingBundle keys, Stream stream, bool armor) { if (keys == null) { throw new ArgumentNullException(nameof(keys)); } if (stream == null) { throw new ArgumentNullException(nameof(stream)); } if (armor) { using (var armored = new ArmoredOutputStream(stream)) { armored.SetHeader("Version", null); keys.Encode(armored); armored.Flush(); } } else { keys.Encode(stream); } }
private PgpPublicKey GetPublicKey(string public_key_path) { PgpPublicKey public_key = null; using (Stream keyin = File.OpenRead(public_key_path)) { using (Stream public_key_stream = PgpUtilities.GetDecoderStream(keyin)) { PgpPublicKeyRingBundle public_key_bundle = new PgpPublicKeyRingBundle(public_key_stream); foreach (PgpPublicKeyRing public_key_ring in public_key_bundle.GetKeyRings()) { foreach (PgpPublicKey key in public_key_ring.GetPublicKeys()) { long modified_key_id = key.KeyId & 0x00000000FFFFFFFF; if (modified_key_id == m_KeyId) { public_key = key; break; } } } if (public_key == null) { throw new Exception("The public key value is null"); } } return(public_key); } }
private List <PgpPublicKey> GetAllSignatureKeys() { List <PgpPublicKey> PgpSignatureKeys = new List <PgpPublicKey>(); foreach (var publicKeyStream in this.SignatureKeys) { if (publicKeyStream.CanSeek) { publicKeyStream.Seek(0, SeekOrigin.Begin); } PgpPublicKeyRingBundle pgpPub = new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(publicKeyStream)); foreach (PgpPublicKeyRing keyRing in pgpPub.GetKeyRings()) { foreach (PgpPublicKey key in keyRing.GetPublicKeys()) { if (key.IsEncryptionKey) { PgpSignatureKeys.Add(key); } } } } return(PgpSignatureKeys); }
public String EncryptKeycode(String publicKeyStr, String unencryptedKeycode) { byte[] unencryptedByteArray = System.Text.Encoding.ASCII.GetBytes(unencryptedKeycode); byte[] decodedPublicKey = System.Text.Encoding.ASCII.GetBytes(publicKeyStr); PgpPublicKey key = null; Stream decodedStream = PgpUtilities.GetDecoderStream(new MemoryStream(decodedPublicKey)); PgpPublicKeyRingBundle pubRings = new PgpPublicKeyRingBundle(decodedStream); foreach (PgpPublicKeyRing pgpPub in pubRings.GetKeyRings()) { foreach (PgpPublicKey publicKey in pgpPub.GetPublicKeys()) { if (publicKey.IsEncryptionKey) { key = publicKey; break; } } } if (key == null) { throw new SendSafely.Exceptions.InvalidKeyException("Can't find encryption key in key ring."); } PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Aes256, true); cPk.AddMethod(key); PgpLiteralDataGenerator lData = new PgpLiteralDataGenerator(); // Write the data to a literal MemoryStream bOut; using (bOut = new MemoryStream()) { using (Stream pOut = lData.Open(bOut, PgpLiteralData.Binary, PgpLiteralData.Console, unencryptedByteArray.Length, DateTime.Now)) { pOut.Write(unencryptedByteArray, 0, unencryptedByteArray.Length); } } lData.Close(); byte[] bytes = bOut.ToArray(); MemoryStream encOut = new MemoryStream(); using (ArmoredOutputStream armoredOut = new ArmoredOutputStream(encOut)) { using (Stream cOut = cPk.Open(armoredOut, bytes.Length)) { cOut.Write(bytes, 0, bytes.Length); } } return(System.Text.Encoding.Default.GetString(encOut.ToArray())); }
/// <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(); } }
public static PgpPublicKey ImportPublicKey(this Stream publicIn) { var pubRings = new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(publicIn)).GetKeyRings().OfType <PgpPublicKeyRing>(); var pubKeys = pubRings.SelectMany(x => x.GetPublicKeys().OfType <PgpPublicKey>()); var pubKey = pubKeys.FirstOrDefault(); return(pubKey); }
/// <summary> /// Verifys the signature of a RPM package. /// </summary> /// <param name="pgpPublicKey"> /// A <see cref="Stream"/> which contains the public key used to verify the data. /// </param> /// <returns> /// <see langword="true"/> if the verification was successful; otherwise, <see langword="false"/>. /// </returns> public bool Verify(Stream pgpPublicKeyStream) { var bundle = new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(pgpPublicKeyStream)); var publicKeyRings = bundle.GetKeyRings().OfType<PgpPublicKeyRing>(); var publicKeys = publicKeyRings.SelectMany(x => x.GetPublicKeys().OfType<PgpPublicKey>()); var publicKey = publicKeys.FirstOrDefault(); return Verify(publicKey); }
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 PgpPublicKeyRingBundle ReadPublicKeBundle(string fileName) { using (Stream keyIn = File.OpenRead(fileName)) { var pgpPub = new PgpPublicKeyRingBundle( PgpUtilities.GetDecoderStream(keyIn)); return(pgpPub); } }
/// <summary> /// Imports a public pgp keyring. /// </summary> /// <remarks> /// Imports a public pgp keyring. /// </remarks> /// <param name="keyring">The pgp keyring.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="keyring"/> is <c>null</c>. /// </exception> public virtual void Import(PgpPublicKeyRing keyring) { if (keyring == null) { throw new ArgumentNullException(nameof(keyring)); } PublicKeyRingBundle = PgpPublicKeyRingBundle.AddPublicKeyRing(PublicKeyRingBundle, keyring); SavePublicKeyRingBundle(); }
public static PgpPublicKey FindPublicKeyByKeyId(PgpPublicKeyRingBundle pgpPub, long keyId) { var pgpPubKey = pgpPub.GetPublicKey(keyId); if (pgpPubKey == null) { return(null); } return(pgpPubKey); }
private PgpPublicKey GetFirstPublicKey(PgpPublicKeyRingBundle publicKeyRingBundle) { foreach (PgpPublicKeyRing keyRing in publicKeyRingBundle.GetKeyRings()) { PgpPublicKey key = keyRing.GetPublicKeys().Cast <PgpPublicKey>().Where(i => i.IsEncryptionKey).FirstOrDefault(); if (key != null) { return(key); } } return(null); }
/// <summary> /// Exports the specified public keys. /// </summary> /// <remarks> /// Exports the specified public keys. /// </remarks> /// <returns>A new <see cref="MimePart"/> instance containing the exported public keys.</returns> /// <param name="keys">The public keys to export.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="keys"/> is <c>null</c>. /// </exception> public MimePart Export(IEnumerable <PgpPublicKey> keys) { if (keys == null) { throw new ArgumentNullException(nameof(keys)); } var keyrings = keys.Select(key => new PgpPublicKeyRing(key.GetEncoded())); var bundle = new PgpPublicKeyRingBundle(keyrings); return(Export(bundle)); }
public PgpPublicKey GetPublicKeyForEncryption(string email) { using (var inputStream = File.OpenRead(Context.PublicKeyRingFile)) { using (var decoderStream = PgpUtilities.GetDecoderStream(inputStream)) { var pgpPub = new PgpPublicKeyRingBundle(decoderStream); var emailSearch = "<" + email.ToLower().Trim() + ">"; foreach (PgpPublicKeyRing kRing in pgpPub.GetKeyRings()) { foreach (PgpPublicKey k in kRing.GetPublicKeys()) { if (!IsEncryptionKey(k)) { continue; } if (!k.IsMasterKey) { foreach (PgpSignature sig in k.GetSignaturesOfType(24)) { var pubKey = this.GetPublicKey(sig.KeyId); if (!pubKey.IsMasterKey) { continue; } foreach (string id in pubKey.GetUserIds()) { if (id.ToLower().IndexOf(emailSearch) > -1) { return(k); } } } } foreach (string id in k.GetUserIds()) { if (id.ToLower().IndexOf(emailSearch) > -1) { return(k); } } } } return(null); } } }
/// <inheritdoc/> public void ImportKey(ArraySegment <byte> data) { var ring = ParseObject <PgpPublicKeyRing>(PgpUtilities.GetDecoderStream(data.ToStream())); try { PublicBundle = PgpPublicKeyRingBundle.AddPublicKeyRing(PublicBundle, ring); } catch (ArgumentException) { // Bundle already contains key } }
public static string ReadKeyDirectly(string stringKeyData) { Stream fs = new MemoryStream(System.Text.Encoding.ASCII.GetBytes(stringKeyData)); fs.Seek(0, SeekOrigin.Begin); PgpPublicKeyRingBundle pubRings = new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(fs)); foreach (PgpPublicKeyRing pubRing in pubRings.GetKeyRings()) { return(Convert.ToBase64String(pubRing.GetEncoded())); } return(null); }
private PgpPublicKey ReadPublicKey(Stream publicKeyStream) { using (Stream inputStream = PgpUtilities.GetDecoderStream(publicKeyStream)) { PgpPublicKeyRingBundle publicKeyRingBundle = new PgpPublicKeyRingBundle(inputStream); PgpPublicKey foundKey = GetFirstPublicKey(publicKeyRingBundle); if (foundKey != null) { return(foundKey); } } throw new ArgumentException("No encryption key found in public key ring."); }
/** * A simple routine that opens a key ring file and loads the first available key * suitable for encryption. * * @param input * @return * @throws IOException * @throws PGPException */ internal static PgpPublicKey ReadPublicKey(Stream input, string userId) { PgpPublicKeyRingBundle pgpPub = new PgpPublicKeyRingBundle( PgpUtilities.GetDecoderStream(input)); foreach (PgpPublicKeyRing keyRing in pgpPub.GetKeyRings()) { foreach (PgpPublicKey key in keyRing.GetPublicKeys()) { if (key.IsEncryptionKey && key.GetUserIds().OfType<string>().Any(x => x != null && x.Contains(userId))) { return key; } } } throw new ArgumentException("Can't find encryption key in key ring."); }
public static void Main(string[] args) { PgpPublicKeyRingBundle pubRings; using (Stream fs = File.OpenRead(args[0])) { pubRings = new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(fs)); } foreach (PgpPublicKeyRing pgpPub in pubRings.GetKeyRings()) { try { //PgpPublicKey pubKey = pgpPub.GetPublicKey(); } catch (Exception e) { Console.Error.WriteLine(e.Message); Console.Error.WriteLine(e.StackTrace); continue; } var first = true; foreach (PgpPublicKey pgpKey in pgpPub.GetPublicKeys()) { if (first) { Console.WriteLine("Key ID: " + pgpKey.KeyId.ToString("X")); first = false; } else { Console.WriteLine("Key ID: " + pgpKey.KeyId.ToString("X") + " (subkey)"); } Console.WriteLine(" Algorithm: " + GetAlgorithm(pgpKey.Algorithm)); Console.WriteLine(" Fingerprint: " + Hex.ToHexString(pgpKey.GetFingerprint())); } } }
/** * A simple routine that opens a key ring file and loads the first available key * suitable for encryption. * * @param input * @return * @throws IOException * @throws PGPException */ internal static PgpPublicKey ReadPublicKey(Stream input) { PgpPublicKeyRingBundle pgpPub = new PgpPublicKeyRingBundle( PgpUtilities.GetDecoderStream(input)); // // we just loop through the collection till we find a key suitable for encryption, in the real // world you would probably want to be a bit smarter about this. // foreach (PgpPublicKeyRing keyRing in pgpPub.GetKeyRings()) { foreach (PgpPublicKey key in keyRing.GetPublicKeys()) { if (key.IsEncryptionKey) { return key; } } } throw new ArgumentException("Can't find encryption key in key ring."); }
public override void PerformTest() { Stream fIn = SimpleTest.GetTestDataAsStream("openpgp.bigpub.asc"); Stream keyIn = PgpUtilities.GetDecoderStream(fIn); PgpPublicKeyRingBundle pubRings = new PgpPublicKeyRingBundle(keyIn); }
public void PerformTest1() { PgpPublicKeyRingBundle pubRings = new PgpPublicKeyRingBundle(pub1); int count = 0; foreach (PgpPublicKeyRing pgpPub1 in pubRings.GetKeyRings()) { count++; int keyCount = 0; byte[] bytes = pgpPub1.GetEncoded(); PgpPublicKeyRing pgpPub2 = new PgpPublicKeyRing(bytes); foreach (PgpPublicKey pubKey in pgpPub2.GetPublicKeys()) { keyCount++; foreach (PgpSignature sig in pubKey.GetSignatures()) { if (sig == null) Fail("null signature found"); } } if (keyCount != 2) { Fail("wrong number of public keys"); } } if (count != 1) { Fail("wrong number of public keyrings"); } // // exact match // count = 0; foreach (PgpPublicKeyRing pgpPub3 in pubRings.GetKeyRings("test (Test key) <*****@*****.**>")) { if (pgpPub3 == null) Fail("null keyring found"); count++; } if (count != 1) { Fail("wrong number of public keyrings on exact match"); } // // partial match 1 expected // count = 0; foreach (PgpPublicKeyRing pgpPub4 in pubRings.GetKeyRings("test", true)) { if (pgpPub4 == null) Fail("null keyring found"); count++; } if (count != 1) { Fail("wrong number of public keyrings on partial match 1"); } // // partial match 0 expected // count = 0; foreach (PgpPublicKeyRing pgpPub5 in pubRings.GetKeyRings("XXX", true)) { if (pgpPub5 == null) Fail("null keyring found"); count++; } if (count != 0) { Fail("wrong number of public keyrings on partial match 0"); } // // case-insensitive partial match // count = 0; foreach (PgpPublicKeyRing pgpPub6 in pubRings.GetKeyRings("*****@*****.**", true, true)) { if (pgpPub6 == null) Fail("null keyring found"); count++; } if (count != 1) { Fail("wrong number of public keyrings on case-insensitive partial match"); } PgpSecretKeyRingBundle secretRings = new PgpSecretKeyRingBundle(sec1); count = 0; foreach (PgpSecretKeyRing pgpSec1 in secretRings.GetKeyRings()) { count++; int keyCount = 0; byte[] bytes = pgpSec1.GetEncoded(); PgpSecretKeyRing pgpSec2 = new PgpSecretKeyRing(bytes); foreach (PgpSecretKey k in pgpSec2.GetSecretKeys()) { keyCount++; PgpPublicKey pk = k.PublicKey; pk.GetSignatures(); byte[] pkBytes = pk.GetEncoded(); PgpPublicKeyRing pkR = new PgpPublicKeyRing(pkBytes); } if (keyCount != 2) { Fail("wrong number of secret keys"); } } if (count != 1) { Fail("wrong number of secret keyrings"); } // // exact match // count = 0; foreach (PgpSecretKeyRing o1 in secretRings.GetKeyRings("test (Test key) <*****@*****.**>")) { if (o1 == null) Fail("null keyring found"); count++; } if (count != 1) { Fail("wrong number of secret keyrings on exact match"); } // // partial match 1 expected // count = 0; foreach (PgpSecretKeyRing o2 in secretRings.GetKeyRings("test", true)) { if (o2 == null) Fail("null keyring found"); count++; } if (count != 1) { Fail("wrong number of secret keyrings on partial match 1"); } // // exact match 0 expected // count = 0; foreach (PgpSecretKeyRing o3 in secretRings.GetKeyRings("test", false)) { if (o3 == null) Fail("null keyring found"); count++; } if (count != 0) { Fail("wrong number of secret keyrings on partial match 0"); } // // case-insensitive partial match // count = 0; foreach (PgpSecretKeyRing o4 in secretRings.GetKeyRings("*****@*****.**", true, true)) { if (o4 == null) Fail("null keyring found"); count++; } if (count != 1) { Fail("wrong number of secret keyrings on case-insensitive partial match"); } }
public void PerformTest2() { PgpPublicKeyRingBundle pubRings = new PgpPublicKeyRingBundle(pub2); int count = 0; byte[] encRing = pubRings.GetEncoded(); pubRings = new PgpPublicKeyRingBundle(encRing); foreach (PgpPublicKeyRing pgpPub1 in pubRings.GetKeyRings()) { count++; int keyCount = 0; byte[] bytes = pgpPub1.GetEncoded(); PgpPublicKeyRing pgpPub2 = new PgpPublicKeyRing(bytes); foreach (PgpPublicKey pk in pgpPub2.GetPublicKeys()) { byte[] pkBytes = pk.GetEncoded(); PgpPublicKeyRing pkR = new PgpPublicKeyRing(pkBytes); keyCount++; } if (keyCount != 2) { Fail("wrong number of public keys"); } } if (count != 2) { Fail("wrong number of public keyrings"); } PgpSecretKeyRingBundle secretRings2 = new PgpSecretKeyRingBundle(sec2); count = 0; encRing = secretRings2.GetEncoded(); PgpSecretKeyRingBundle secretRings = new PgpSecretKeyRingBundle(encRing); foreach (PgpSecretKeyRing pgpSec1 in secretRings2.GetKeyRings()) { count++; int keyCount = 0; byte[] bytes = pgpSec1.GetEncoded(); PgpSecretKeyRing pgpSec2 = new PgpSecretKeyRing(bytes); foreach (PgpSecretKey k in pgpSec2.GetSecretKeys()) { keyCount++; PgpPublicKey pk = k.PublicKey; if (pk.KeyId == -1413891222336124627L) { int sCount = 0; foreach (PgpSignature pgpSignature in pk.GetSignaturesOfType(PgpSignature.SubkeyBinding)) { int type = pgpSignature.SignatureType; if (type != PgpSignature.SubkeyBinding) { Fail("failed to return correct signature type"); } sCount++; } if (sCount != 1) { Fail("failed to find binding signature"); } } pk.GetSignatures(); if (k.KeyId == -4049084404703773049L || k.KeyId == -1413891222336124627L) { k.ExtractPrivateKey(sec2pass1); } else if (k.KeyId == -6498553574938125416L || k.KeyId == 59034765524361024L) { k.ExtractPrivateKey(sec2pass2); } } if (keyCount != 2) { Fail("wrong number of secret keys"); } } if (count != 2) { Fail("wrong number of secret keyrings"); } }
public void PerformTest3() { PgpPublicKeyRingBundle pubRings = new PgpPublicKeyRingBundle(pub3); int count = 0; byte[] encRing = pubRings.GetEncoded(); pubRings = new PgpPublicKeyRingBundle(encRing); foreach (PgpPublicKeyRing pgpPub1 in pubRings.GetKeyRings()) { count++; int keyCount = 0; byte[] bytes = pgpPub1.GetEncoded(); PgpPublicKeyRing pgpPub2 = new PgpPublicKeyRing(bytes); foreach (PgpPublicKey pubK in pgpPub2.GetPublicKeys()) { keyCount++; pubK.GetSignatures(); } if (keyCount != 2) { Fail("wrong number of public keys"); } } if (count != 1) { Fail("wrong number of public keyrings"); } PgpSecretKeyRingBundle secretRings2 = new PgpSecretKeyRingBundle(sec3); count = 0; encRing = secretRings2.GetEncoded(); PgpSecretKeyRingBundle secretRings = new PgpSecretKeyRingBundle(encRing); foreach (PgpSecretKeyRing pgpSec1 in secretRings2.GetKeyRings()) { count++; int keyCount = 0; byte[] bytes = pgpSec1.GetEncoded(); PgpSecretKeyRing pgpSec2 = new PgpSecretKeyRing(bytes); foreach (PgpSecretKey k in pgpSec2.GetSecretKeys()) { keyCount++; k.ExtractPrivateKey(sec3pass1); } if (keyCount != 2) { Fail("wrong number of secret keys"); } } if (count != 1) { Fail("wrong number of secret keyrings"); } }
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 void PerformTest8() { PgpPublicKeyRingBundle pubRings = new PgpPublicKeyRingBundle(pub8); int count = 0; byte[] encRing = pubRings.GetEncoded(); pubRings = new PgpPublicKeyRingBundle(encRing); foreach (PgpPublicKeyRing pgpPub1 in pubRings.GetKeyRings()) { count++; int keyCount = 0; byte[] bytes = pgpPub1.GetEncoded(); PgpPublicKeyRing pgpPub2 = new PgpPublicKeyRing(bytes); foreach (PgpPublicKey o in pgpPub2.GetPublicKeys()) { if (o == null) Fail("null key found"); keyCount++; } if (keyCount != 2) { Fail("wrong number of public keys"); } } if (count != 2) { Fail("wrong number of public keyrings"); } PgpSecretKeyRingBundle secretRings1 = new PgpSecretKeyRingBundle(sec8); count = 0; encRing = secretRings1.GetEncoded(); PgpSecretKeyRingBundle secretRings2 = new PgpSecretKeyRingBundle(encRing); foreach (PgpSecretKeyRing pgpSec1 in secretRings1.GetKeyRings()) { count++; int keyCount = 0; byte[] bytes = pgpSec1.GetEncoded(); PgpSecretKeyRing pgpSec2 = new PgpSecretKeyRing(bytes); foreach (PgpSecretKey k in pgpSec2.GetSecretKeys()) { keyCount++; k.ExtractPrivateKey(sec8pass); } if (keyCount != 2) { Fail("wrong number of secret keys"); } } if (count != 1) { Fail("wrong number of secret keyrings"); } }
public void PerformTest6() { PgpPublicKeyRingBundle pubRings = new PgpPublicKeyRingBundle(pub6); foreach (PgpPublicKeyRing pgpPub in pubRings.GetKeyRings()) { foreach (PgpPublicKey k in pgpPub.GetPublicKeys()) { if (k.KeyId == 0x5ce086b5b5a18ff4L) { int count = 0; foreach (PgpSignature sig in k.GetSignaturesOfType(PgpSignature.SubkeyRevocation)) { if (sig == null) Fail("null signature found"); count++; } if (count != 1) { Fail("wrong number of revocations in test6."); } } } } byte[] encRing = pubRings.GetEncoded(); }