Often a PGP key ring file is made up of a succession of master/sub-key key rings. If you want to read an entire public key file in one hit this is the class for you.
Exemplo n.º 1
15
        /// <summary>
        /// Initializes a new instance of the <see cref="MimeKit.Cryptography.OpenPgpContext"/> class.
        /// </summary>
        /// <param name="pubring">The public keyring file path.</param>
        /// <param name="secring">The secret keyring file path.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <para><paramref name="pubring"/> is <c>null</c>.</para>
        /// <para>-or-</para>
        /// <para><paramref name="secring"/> is <c>null</c>.</para>
        /// </exception>
        /// <exception cref="System.IO.IOException">
        /// An error occurred while reading one of the keyring files.
        /// </exception>
        /// <exception cref="Org.BouncyCastle.Bcpg.OpenPgp.PgpException">
        /// An error occurred while parsing one of the keyring files.
        /// </exception>
        protected OpenPgpContext(string pubring, string secring)
        {
            if (pubring == null)
                throw new ArgumentNullException ("pubring");

            if (secring == null)
                throw new ArgumentNullException ("secring");

            PublicKeyRingPath = pubring;
            SecretKeyRingPath = secring;

            if (File.Exists (pubring)) {
                using (var file = File.OpenRead (pubring)) {
                    PublicKeyRingBundle = new PgpPublicKeyRingBundle (file);
                }
            } else {
                PublicKeyRingBundle = new PgpPublicKeyRingBundle (new byte[0]);
            }

            if (File.Exists (secring)) {
                using (var file = File.OpenRead (secring)) {
                    SecretKeyRingBundle = new PgpSecretKeyRingBundle (file);
                }
            } else {
                SecretKeyRingBundle = new PgpSecretKeyRingBundle (new byte[0]);
            }
        }
Exemplo n.º 2
1
 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;
     }
     return null;
 }
 private PgpPublicKey ReadPublicKey(string publicKeyPath)
 {
     using (Stream keyIn = File.OpenRead(publicKeyPath))
     {
         using (Stream inputStream = PgpUtilities.GetDecoderStream(keyIn))
         {
             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.");
 }
        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;
        }
Exemplo n.º 5
0
        public static PgpPublicKeyRingBundle RemovePublicKeyRing(PgpPublicKeyRingBundle bundle, PgpPublicKeyRing publicKeyRing)
        {
            //IL_0024: Unknown result type (might be due to invalid IL or missing references)
            long keyId = publicKeyRing.GetPublicKey().KeyId;

            if (!bundle.pubRings.Contains((object)keyId))
            {
                throw new ArgumentException("Bundle does not contain a key with a keyId for the passed in ring.");
            }
            IDictionary val = Platform.CreateHashtable(bundle.pubRings);

            global::System.Collections.IList list = Platform.CreateArrayList((global::System.Collections.ICollection)bundle.order);
            val.Remove((object)keyId);
            list.Remove((object)keyId);
            return(new PgpPublicKeyRingBundle(val, list));
        }
		/**
        * 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.");
            }
        }
Exemplo n.º 7
0
		public static void Main(
			string[] args)
        {
			Stream fs = File.OpenRead(args[0]);

			//
            // Read the public key rings
            //
            PgpPublicKeyRingBundle pubRings = new PgpPublicKeyRingBundle(
                PgpUtilities.GetDecoderStream(fs));

			fs.Close();

			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;
                }

				bool 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()));
                }
            }
        }
        public static PgpPublicKey ReadPublicKey(Stream inputStream)
        {
            inputStream = PgpUtilities.GetDecoderStream(inputStream);
            PgpPublicKeyRingBundle pgpPub = new PgpPublicKeyRingBundle(inputStream);

            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.");
        }
Exemplo n.º 9
0
        /// <summary>
        /// Return a new bundle containing the contents of the passed in bundle with
        /// the passed in public key ring removed.
        /// </summary>
        /// <param name="bundle">The <c>PgpPublicKeyRingBundle</c> the key ring is to be removed from.</param>
        /// <param name="publicKeyRing">The key ring to be removed.</param>
        /// <returns>A new <c>PgpPublicKeyRingBundle</c> not containing the passed in key ring.</returns>
        /// <exception cref="ArgumentException">If the keyId for the passed in key ring is not present.</exception>
        public static PgpPublicKeyRingBundle RemovePublicKeyRing(
            PgpPublicKeyRingBundle bundle,
            PgpPublicKeyRing publicKeyRing)
        {
            long key = publicKeyRing.GetPublicKey().KeyId;

            if (!bundle.pubRings.Contains(key))
            {
                throw new ArgumentException("Bundle does not contain a key with a keyId for the passed in ring.");
            }

            IDictionary newPubRings = Platform.CreateHashtable(bundle.pubRings);
            IList       newOrder    = Platform.CreateArrayList(bundle.order);

            newPubRings.Remove(key);
            newOrder.Remove(key);

            return(new PgpPublicKeyRingBundle(newPubRings, newOrder));
        }
Exemplo n.º 10
0
        /// <summary>
        /// Return a new bundle containing the contents of the passed in bundle and
        /// the passed in public key ring.
        /// </summary>
        /// <param name="bundle">The <c>PgpPublicKeyRingBundle</c> the key ring is to be added to.</param>
        /// <param name="publicKeyRing">The key ring to be added.</param>
        /// <returns>A new <c>PgpPublicKeyRingBundle</c> merging the current one with the passed in key ring.</returns>
        /// <exception cref="ArgumentException">If the keyId for the passed in key ring is already present.</exception>
        public static PgpPublicKeyRingBundle AddPublicKeyRing(
            PgpPublicKeyRingBundle bundle,
            PgpPublicKeyRing publicKeyRing)
        {
            long key = publicKeyRing.GetPublicKey().KeyId;

            if (bundle.pubRings.Contains(key))
            {
                throw new ArgumentException("Bundle already contains a key with a keyId for the passed in ring.");
            }

            IDictionary newPubRings = new Hashtable(bundle.pubRings);
            ArrayList   newOrder    = new ArrayList(bundle.order);

            newPubRings[key] = publicKeyRing;

            newOrder.Add(key);

            return(new PgpPublicKeyRingBundle(newPubRings, newOrder));
        }
Exemplo n.º 11
0
		/**
        * 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));
            PgpPublicKey				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.");
            }
        }
Exemplo n.º 12
0
		static void Main(string[] args)
		{
			//password = args[0].ToCharArray();

			//var context = new CryptoContext(PasswordCallback, "AES-128", "SHA-1");
			//var crypto = new PgpCrypto(context);
			try
			{
				using (var inputStream = File.OpenRead(@"C:\projects\OutlookPrivacyPlugin\Deja.Crypto.Test\private\andrew-pubring.gpg"))
				using (var decodeStream = PgpUtilities.GetDecoderStream(inputStream))
				{
					var pgpPub = new PgpPublicKeyRingBundle(decodeStream);

					foreach (PgpPublicKeyRing kRing in pgpPub.GetKeyRings())
					{
						// The master key is normally the first key returned.
						var masterKey = kRing.GetPublicKey();
						if (!masterKey.IsMasterKey)
						{
							foreach (PgpPublicKey k in kRing.GetPublicKeys())
								if (k.IsMasterKey)
									Console.WriteLine("{0:X}", k.KeyId);
						}

						foreach (PgpPublicKey k in kRing.GetPublicKeys())
						{
							Console.WriteLine("{0:X}", k.KeyId);
						}
					}
				}
			}
			catch (Exception)
			{
				throw;
			}

		}
Exemplo n.º 13
0
    /// <summary>
    /// Encrypt string using a PGP public key
    /// </summary>
    /// <param name="plain">plain text to encrypt</param>
    /// <param name="armoredPublicKey">public key in ASCII "-----BEGIN PGP PUBLIC KEY BLOCK----- .. -----END PGP PUBLIC KEY BLOCK-----" format</param>
    /// <returns>PGP message string</returns>
    public static string PGPEncrypt(string plain, string armoredPublicKey)
    {
      // encode data
      byte[] data = Encoding.UTF8.GetBytes(plain);

      // create the WinAuth public key
      PgpPublicKey publicKey = null;
      using (MemoryStream ms = new MemoryStream(Encoding.ASCII.GetBytes(armoredPublicKey)))
      {
        using (Stream dis = PgpUtilities.GetDecoderStream(ms))
        {
          PgpPublicKeyRingBundle bundle = new PgpPublicKeyRingBundle(dis);
          foreach (PgpPublicKeyRing keyring in bundle.GetKeyRings())
          {
            foreach (PgpPublicKey key in keyring.GetPublicKeys())
            {
              if (key.IsEncryptionKey == true && key.IsRevoked() == false)
              {
                publicKey = key;
                break;
              }
            }
          }
        }
      }

      // encrypt the data using PGP
      using (MemoryStream encryptedStream = new MemoryStream())
      {
        using (ArmoredOutputStream armored = new ArmoredOutputStream(encryptedStream))
        {
          PgpEncryptedDataGenerator pedg = new PgpEncryptedDataGenerator(Org.BouncyCastle.Bcpg.SymmetricKeyAlgorithmTag.Cast5, true, new Org.BouncyCastle.Security.SecureRandom());
          pedg.AddMethod(publicKey);
          using (Stream pedgStream = pedg.Open(armored, new byte[4096]))
          {
            PgpCompressedDataGenerator pcdg = new PgpCompressedDataGenerator(Org.BouncyCastle.Bcpg.CompressionAlgorithmTag.Zip);
            using (Stream pcdgStream = pcdg.Open(pedgStream))
            {
              PgpLiteralDataGenerator pldg = new PgpLiteralDataGenerator();
              using (Stream encrypter = pldg.Open(pcdgStream, PgpLiteralData.Binary, "", (long)data.Length, DateTime.Now))
              {
                encrypter.Write(data, 0, data.Length);
              }
            }
          }
        }

        return Encoding.ASCII.GetString(encryptedStream.ToArray());
      }
    }
        /// <summary>
        /// Return a new bundle containing the contents of the passed in bundle and
        /// the passed in public key ring.
        /// </summary>
        /// <param name="bundle">The <c>PgpPublicKeyRingBundle</c> the key ring is to be added to.</param>
        /// <param name="publicKeyRing">The key ring to be added.</param>
        /// <returns>A new <c>PgpPublicKeyRingBundle</c> merging the current one with the passed in key ring.</returns>
        /// <exception cref="ArgumentException">If the keyId for the passed in key ring is already present.</exception>
        public static PgpPublicKeyRingBundle AddPublicKeyRing(
            PgpPublicKeyRingBundle  bundle,
            PgpPublicKeyRing        publicKeyRing)
        {
            long key = publicKeyRing.GetPublicKey().KeyId;

            if (bundle.pubRings.Contains(key))
            {
                throw new ArgumentException("Bundle already contains a key with a keyId for the passed in ring.");
            }

            IDictionary newPubRings = Platform.CreateHashtable(bundle.pubRings);
            IList newOrder = Platform.CreateArrayList(bundle.order);

            newPubRings[key] = publicKeyRing;

            newOrder.Add(key);

            return new PgpPublicKeyRingBundle(newPubRings, newOrder);
        }
Exemplo n.º 15
0
 private static PgpPublicKey GetFirstPublicKey(PgpPublicKeyRingBundle publicKeyRingBundle)
 {
     foreach (PgpPublicKeyRing kRing in publicKeyRingBundle.GetKeyRings())
     {
         var keys = kRing.GetPublicKeys();
         foreach (var key in keys)
         {
             PgpPublicKey foundKey = (PgpPublicKey)key;
             //PgpPublicKey key = kRing.GetPublicKeys()
             //.Cast<PgpPublicKey>()
             // .Where(k => k.IsEncryptionKey)
             //  .FirstOrDefault();
             if (foundKey != null && foundKey.IsEncryptionKey)
                 return foundKey;
         }
     }
     return null;
 }
Exemplo n.º 16
0
        public static string GetFingerprint(string key)
        {
            string hexString = string.Empty;
            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)
                    {
                        byte[] fing = foundKey.GetFingerprint();
                        hexString = Hex.ToHexString(fing);
                    }
                }
            }
            return hexString;
        }
Exemplo n.º 17
0
        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 ex)
            {
                isValid = false;
            }
            return isValid;
        }
Exemplo n.º 18
0
		/// <summary>
		/// Exports the specified public keys.
		/// </summary>
		/// <remarks>
		/// Exports the specified public keys.
		/// </remarks>
		/// <returns>A new <see cref="MimeKit.MimePart"/> instance containing the exported public keys.</returns>
		/// <param name="keys">The keys.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="keys"/> is <c>null</c>.
		/// </exception>
		public MimePart Export (PgpPublicKeyRingBundle keys)
		{
			if (keys == null)
				throw new ArgumentNullException ("keys");

			var content = new MemoryBlockStream ();

			using (var armored = new ArmoredOutputStream (content)) {
				keys.Encode (armored);
				armored.Flush ();
			}

			content.Position = 0;

			return new MimePart ("application", "pgp-keys") {
				ContentDisposition = new ContentDisposition ("attachment"),
				ContentObject = new ContentObject (content)
			};
		}
		/*
		* 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;
            }
        }
Exemplo n.º 21
0
        public PgpPublicKey LoadPubKey(string path)
        {
            using (FileStream keyStream = File.OpenRead(path)) {
                Stream decStream = PgpUtilities.GetDecoderStream (keyStream);
                PgpPublicKeyRingBundle pgpPub = new PgpPublicKeyRingBundle (decStream);

                foreach (PgpPublicKeyRing keyRing in pgpPub.GetKeyRings()) {
                    foreach (PgpPublicKey key in keyRing.GetPublicKeys()) {
                        if (key.IsEncryptionKey) {
                            return key;
                        }
                    }
                }
                throw new ArgumentException ("Key not found");
            }
        }
        public PgpPublicKey GetPublicKey(long KeyId)
        {
            using (var inputStream = File.OpenRead(Context.PublicKeyRingFile))
            {
                using (var decodeStream = PgpUtilities.GetDecoderStream(inputStream))
                {
                    var pgpPub = new PgpPublicKeyRingBundle(decodeStream);

                    foreach (PgpPublicKeyRing kRing in pgpPub.GetKeyRings())
                    {
                        foreach (PgpPublicKey k in kRing.GetPublicKeys())
                        {
                            if (k.KeyId == KeyId)
                                return k;
                        }
                    }

                    return null;
                }
            }
        }
        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;
                }
            }
        }
Exemplo n.º 24
0
		/// <summary>
		/// Imports a public pgp keyring bundle.
		/// </summary>
		/// <remarks>
		/// Imports a public pgp keyring bundle.
		/// </remarks>
		/// <param name="bundle">The pgp keyring bundle.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="bundle"/> is <c>null</c>.
		/// </exception>
		public void Import (PgpPublicKeyRingBundle bundle)
		{
			if (bundle == null)
				throw new ArgumentNullException (nameof (bundle));

			int publicKeysAdded = 0;

			foreach (PgpPublicKeyRing pubring in bundle.GetKeyRings ()) {
				if (!PublicKeyRingBundle.Contains (pubring.GetPublicKey ().KeyId)) {
					PublicKeyRingBundle = PgpPublicKeyRingBundle.AddPublicKeyRing (PublicKeyRingBundle, pubring);
					publicKeysAdded++;
				}
			}

			if (publicKeysAdded > 0)
				SavePublicKeyRingBundle ();
		}
Exemplo n.º 25
0
		/// <summary>
		/// Initializes a new instance of the <see cref="MimeKit.Cryptography.OpenPgpContext"/> class.
		/// </summary>
		/// <remarks>
		/// Creates a new <see cref="OpenPgpContext"/> using the specified public and private keyring paths.
		/// </remarks>
		/// <param name="pubring">The public keyring file path.</param>
		/// <param name="secring">The secret keyring file path.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <para><paramref name="pubring"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="secring"/> is <c>null</c>.</para>
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An error occurred while reading one of the keyring files.
		/// </exception>
		/// <exception cref="Org.BouncyCastle.Bcpg.OpenPgp.PgpException">
		/// An error occurred while parsing one of the keyring files.
		/// </exception>
		protected OpenPgpContext (string pubring, string secring) : this ()
		{
			if (pubring == null)
				throw new ArgumentNullException (nameof (pubring));

			if (secring == null)
				throw new ArgumentNullException (nameof (secring));

			PublicKeyRingPath = pubring;
			SecretKeyRingPath = secring;

			if (File.Exists (pubring)) {
				using (var file = File.Open (pubring, FileMode.Open, FileAccess.Read)) {
					PublicKeyRingBundle = new PgpPublicKeyRingBundle (file);
				}
			} else {
				PublicKeyRingBundle = new PgpPublicKeyRingBundle (new byte[0]);
			}

			if (File.Exists (secring)) {
				using (var file = File.Open (secring, FileMode.Open, FileAccess.Read)) {
					SecretKeyRingBundle = new PgpSecretKeyRingBundle (file);
				}
			} else {
				SecretKeyRingBundle = new PgpSecretKeyRingBundle (new byte[0]);
			}
		}
        public string[] GetPublicKeyUserIdsForEncryption()
        {
            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 (!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(!keyUserIds.Contains(id))
                                            keyUserIds.Add(id);
                                    }
                                }
                            }

                            foreach (string id in k.GetUserIds())
                            {
                                keyUserIds.Add(id);
                            }
                        }
                    }

                    return keyUserIds.ToArray();
                }
            }
        }
Exemplo n.º 27
0
        /// <summary>
        /// A simple routine that opens a key ring file and loads the first available key suitable for encryption.
        /// </summary>
        /// <param name="inputStream">The input stream.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentException">Can't find encryption key in key ring.</exception>
        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.");
        }
        /// <summary>
        /// Return a new bundle containing the contents of the passed in bundle with
        /// the passed in public key ring removed.
        /// </summary>
        /// <param name="bundle">The <c>PgpPublicKeyRingBundle</c> the key ring is to be removed from.</param>
        /// <param name="publicKeyRing">The key ring to be removed.</param>
        /// <returns>A new <c>PgpPublicKeyRingBundle</c> not containing the passed in key ring.</returns>
        /// <exception cref="ArgumentException">If the keyId for the passed in key ring is not present.</exception>
        public static PgpPublicKeyRingBundle RemovePublicKeyRing(
            PgpPublicKeyRingBundle	bundle,
            PgpPublicKeyRing		publicKeyRing)
        {
            long key = publicKeyRing.GetPublicKey().KeyId;

            if (!bundle.pubRings.Contains(key))
            {
                throw new ArgumentException("Bundle does not contain a key with a keyId for the passed in ring.");
            }

            IDictionary newPubRings = new Hashtable(bundle.pubRings);
            ArrayList newOrder = new ArrayList(bundle.order);

            newPubRings.Remove(key);
            newOrder.Remove(key);

            return new PgpPublicKeyRingBundle(newPubRings, newOrder);
        }
Exemplo n.º 29
0
        public void VerifySignature(Stream input, string outputpath)
        {
            input = PgpUtilities.GetDecoderStream(input);
            PgpObjectFactory pgpObjF = new PgpObjectFactory(input);

            //IList collection = pgpObjF.AllPgpObjects();

            PgpEncryptedDataList enc = (PgpEncryptedDataList) pgpObjF.NextPgpObject();

            PgpPrivateKey sKey = null;
            PgpPublicKeyEncryptedData pbe = null;
            PgpSecretKeyRingBundle pgpSec = new PgpSecretKeyRingBundle(PgpUtilities.
                GetDecoderStream(File.OpenRead(m_encryptionKeys.PrivateKeyPathd)));

            foreach (PgpPublicKeyEncryptedData pked in enc.GetEncryptedDataObjects())
            {
                sKey = FindSecretKey(pgpSec, pked.KeyId, m_encryptionKeys.PassPhrase.ToCharArray());

                if (sKey != null)
                {
                    pbe = pked;
                    break;
                }
            }

            if (sKey == null)
            {
                throw new ArgumentException("secret key for message not found.");
            }

            Stream clear = pbe.GetDataStream(sKey);
            PgpObjectFactory plainFact = new PgpObjectFactory(clear);
            PgpCompressedData cData = (PgpCompressedData)plainFact.NextPgpObject();
            PgpObjectFactory pgpFact = new PgpObjectFactory(cData.GetDataStream());
            PgpObject message = pgpFact.NextPgpObject();

            if (message is PgpOnePassSignatureList)
            {
                PgpOnePassSignatureList p1 = (PgpOnePassSignatureList)message;
                PgpOnePassSignature ops = p1[0];

                PgpLiteralData p2 = (PgpLiteralData)pgpFact.NextPgpObject();
                Stream dIn = p2.GetInputStream();

                PgpPublicKeyRingBundle pgpRing = new PgpPublicKeyRingBundle(PgpUtilities.
                            GetDecoderStream(File.OpenRead(m_encryptionKeys.PublicKeyPathd)));
                PgpPublicKey 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))
                {

                    throw new PgpException("signature verified.");
                }
                else
                {

                    throw new PgpException("signature verification failed.");
                }

            }
        }
Exemplo n.º 30
0
		/// <summary>
		/// Imports public pgp keys from the specified stream.
		/// </summary>
		/// <remarks>
		/// Imports public pgp keys from the specified stream.
		/// </remarks>
		/// <param name="stream">The raw key data.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="stream"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// <para>An error occurred while parsing the raw key-ring data</para>
		/// <para>-or-</para>
		/// <para>An error occured while saving the public key-ring bundle.</para>
		/// </exception>
		public override void Import (Stream stream)
		{
			if (stream == null)
				throw new ArgumentNullException ("stream");

			using (var armored = new ArmoredInputStream (stream)) {
				var imported = new PgpPublicKeyRingBundle (armored);
				if (imported.Count == 0)
					return;

				int publicKeysAdded = 0;

				foreach (PgpPublicKeyRing pubring in imported.GetKeyRings ()) {
					if (!PublicKeyRingBundle.Contains (pubring.GetPublicKey ().KeyId)) {
						PublicKeyRingBundle = PgpPublicKeyRingBundle.AddPublicKeyRing (PublicKeyRingBundle, pubring);
						publicKeysAdded++;
					}
				}

				if (publicKeysAdded > 0)
					SavePublicKeyRingBundle ();
			}
		}
Exemplo n.º 31
0
		/// <summary>
		/// Exports the specified public keys.
		/// </summary>
		/// <remarks>
		/// Exports the specified public keys.
		/// </remarks>
		/// <returns>A new <see cref="MimeKit.MimePart"/> instance containing the exported public keys.</returns>
		/// <param name="keys">The keys.</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 ("keys");

			var keyrings = keys.Select (key => new PgpPublicKeyRing (key.GetEncoded ()));
			var bundle = new PgpPublicKeyRingBundle (keyrings);

			return Export (bundle);
		}
Exemplo n.º 32
0
		/// <summary>
		/// Initializes a new instance of the <see cref="MimeKit.Cryptography.OpenPgpContext"/> class.
		/// </summary>
		/// <remarks>
		/// Creates a new <see cref="OpenPgpContext"/> using the specified public and private keyrings.
		/// </remarks>
		/// <param name="pubring">The public keyring.</param>
		/// <param name="secring">The secret keyring.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <para><paramref name="pubring"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="secring"/> is <c>null</c>.</para>
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An error occurred while reading one of the keyring files.
		/// </exception>
		/// <exception cref="Org.BouncyCastle.Bcpg.OpenPgp.PgpException">
		/// An error occurred while parsing one of the keyring files.
		/// </exception>
		protected OpenPgpContext (Stream pubring, Stream secring) : this ()
		{
			if (pubring == null)
				throw new ArgumentNullException ("pubring");

			if (secring == null)
				throw new ArgumentNullException ("secring");

			PublicKeyRing = pubring;
			SecretKeyRing = secring;

			PublicKeyRingBundle = new PgpPublicKeyRingBundle (pubring);
			SecretKeyRingBundle = new PgpSecretKeyRingBundle (secring);

			if (pubring.CanSeek)
				pubring.Seek (0, SeekOrigin.Begin);

			if (secring.CanSeek)
				secring.Seek (0, SeekOrigin.Begin);
		}
        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();
                }
            }
        }