GetKeyRings() public method

Allow enumeration of the secret key rings making up this collection.
public GetKeyRings ( ) : IEnumerable
return IEnumerable
 /// <summary>
 /// Return the first key we can use to encrypt.
 /// Note: A file can contain multiple keys (stored in "key rings")
 /// </summary>
 private PgpSecretKey GetFirstSecretKey(PgpSecretKeyRingBundle secretKeyRingBundle)
 {
     foreach (PgpSecretKeyRing kRing in secretKeyRingBundle.GetKeyRings())
     {
         PgpSecretKey key = kRing.GetSecretKeys()
             .Cast<PgpSecretKey>()
             .Where(k => k.IsSigningKey)
             .FirstOrDefault();
         if (key != null)
             return key;
     }
     return null;
 }
        private static PgpSecretKey ReadSecretKey(Stream inputStream)
        {
            var decodedInputStream = PgpUtilities.GetDecoderStream(inputStream);
            var secretKeyRingBundle = new PgpSecretKeyRingBundle(decodedInputStream);

            // 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 (PgpSecretKeyRing keyRing in secretKeyRingBundle.GetKeyRings())
            {
                foreach (PgpSecretKey key in keyRing.GetSecretKeys())
                {
                    if (key.IsSigningKey)
                        return key;
                }
            }

            throw new ArgumentException("Can't find signing key in key ring.");
        }
        public static bool ValidatePassPhrase(byte[] privateKey, string passPhrase) {
            using (MemoryStream privateKeyStream = new MemoryStream(privateKey))
            {
                PgpSecretKeyRingBundle pgpKeyRing = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(privateKeyStream));
                var items = pgpKeyRing.GetKeyRings();
                foreach (var item in items)
                {
                    try {
                        var i = (PgpSecretKeyRing) item;
                        var key = i.GetSecretKey().ExtractPrivateKey(passPhrase.ToCharArray());
                        return true;
					} catch (Exception ex){
						Insights.Report(ex);
                        return false;
                    }
                }
            }

            return true;
        }
		/// <summary>
		/// Imports secret pgp keys from the specified stream.
		/// </summary>
		/// <remarks>
		/// Imports secret pgp keys from the specified stream.
		/// </remarks>
		/// <param name="rawData">The raw key data.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="rawData"/> 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 virtual void ImportSecretKeys (Stream rawData)
		{
			if (rawData == null)
				throw new ArgumentNullException ("rawData");

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

				int secretKeysAdded = 0;

				foreach (PgpSecretKeyRing secring in imported.GetKeyRings ()) {
					if (!SecretKeyRingBundle.Contains (secring.GetSecretKey ().KeyId)) {
						SecretKeyRingBundle = PgpSecretKeyRingBundle.AddSecretKeyRing (SecretKeyRingBundle, secring);
						secretKeysAdded++;
					}
				}

				if (secretKeysAdded > 0)
					SaveSecretKeyRingBundle ();
			}
		}
Beispiel #5
0
		public static PgpSecretKey ReadSecretKey(
            Stream inputStream)
        {
            inputStream = PgpUtilities.GetDecoderStream(inputStream);

            PgpSecretKeyRingBundle pgpSec = new PgpSecretKeyRingBundle(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.
            //

			foreach (PgpSecretKeyRing kRing in pgpSec.GetKeyRings())
            {
                foreach (PgpSecretKey k in kRing.GetSecretKeys())
                {
                    if (k.IsSigningKey)
                    {
                        return k;
                    }
                }
            }

			throw new ArgumentException("Can't find signing key in key ring.");
        }
		/// <summary>
		/// Imports a secret pgp keyring bundle.
		/// </summary>
		/// <remarks>
		/// Imports a secret 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 (PgpSecretKeyRingBundle bundle)
		{
			if (bundle == null)
				throw new ArgumentNullException (nameof (bundle));

			int secretKeysAdded = 0;

			foreach (PgpSecretKeyRing secring in bundle.GetKeyRings ()) {
				if (!SecretKeyRingBundle.Contains (secring.GetSecretKey ().KeyId)) {
					SecretKeyRingBundle = PgpSecretKeyRingBundle.AddSecretKeyRing (SecretKeyRingBundle, secring);
					secretKeysAdded++;
				}
			}

			if (secretKeysAdded > 0)
				SaveSecretKeyRingBundle ();
		}
        /// <summary>
        /// Return the first key we can use to encrypt.
        /// Note: A file can contain multiple keys (stored in "key rings")
        /// </summary>
        private PgpSecretKey getFirstSecretKey(PgpSecretKeyRingBundle secretKeyRingBundle)
        {
            foreach (PgpSecretKeyRing kRing in secretKeyRingBundle.GetKeyRings())
            {
                // Note: You may need to use something other than the first key
                //  in your key ring. Keep that in mind.
                // ex: .Where(k => !k.IsSigningKey)
                PgpSecretKey key = kRing.GetSecretKeys()
                    .Cast<PgpSecretKey>()
                    //.Where(k => k.IsSigningKey)
                    .Where(k => !k.IsSigningKey)
                    .FirstOrDefault();

                if (key != null)
                {
                    return key;
                }
            }

            return null;
        }
Beispiel #8
0
		private PgpSecretKey readSecretKey(Stream privateKeyStream)
		{
			PgpSecretKeyRingBundle pgpSec;
			try
			{
				pgpSec = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(privateKeyStream));
			}
			catch (Exception e)
			{
				throw new Exception("Invalid private key stream, reason: " + e.Message);
			}
			
			var keyRings = pgpSec.GetKeyRings();
			foreach( PgpSecretKeyRing keyRing in keyRings)
			{
				foreach(PgpSecretKey key in keyRing.GetSecretKeys())
				{
					if( key.IsSigningKey )
						return key;
				}
			}
			
			throw new Exception("Could not find a valid signing key");
		}
        public PgpSecretKey GetSecretKey(long Id)
        {
            using (var inputStream = File.OpenRead(Context.PrivateKeyRingFile))
            {
                using (var decoderStream = PgpUtilities.GetDecoderStream(inputStream))
                {
                    var pgpPub = new PgpSecretKeyRingBundle(decoderStream);

                    foreach (PgpSecretKeyRing kRing in pgpPub.GetKeyRings())
                    {
                        foreach (PgpSecretKey k in kRing.GetSecretKeys())
                        {
                            if (k.KeyId == Id)
                                return k;
                        }
                    }

                    return null;
                }
            }
        }
Beispiel #10
0
 public PgpSecretKey LoadSecKey(string path)
 {
     using (Stream keyIn = File.OpenRead(path)) {
         Stream decStream = PgpUtilities.GetDecoderStream (keyIn);
         PgpSecretKeyRingBundle pgpSec = new PgpSecretKeyRingBundle (decStream);
         foreach (PgpSecretKeyRing keyRing in pgpSec.GetKeyRings()) {
             foreach (PgpSecretKey key in keyRing.GetSecretKeys()) {
                 if (key.IsSigningKey) {
                     return key;
                 }
             }
         }
         throw new ArgumentException ("Can't find signing key in key ring.");
     }
 }
        /// <summary>
        /// Return the first key we can use to encrypt.
        /// Note: A file can contain multiple keys (stored in "key rings")
        /// </summary>
        private PgpSecretKey getFirstSecretKey(PgpSecretKeyRingBundle secretKeyRingBundle)
        {
            foreach (PgpSecretKeyRing kRing in secretKeyRingBundle.GetKeyRings())
            {
                // Note: You may need to use something other than the first key
                //  in your key ring. Keep that in mind.
                // ex: .Where(k => !k.IsSigningKey)
                /*
                PgpSecretKey key = kRing.GetSecretKeys()
                    .Cast<PgpSecretKey>()
                    .Where(k => k.IsSigningKey)
                    .FirstOrDefault();

                if (key != null)
                {
                    return key;
                }
                */
                IEnumerator ikeys = kRing.GetSecretKeys().GetEnumerator();
                if(ikeys.MoveNext()){
                    PgpSecretKey key=(PgpSecretKey)ikeys.Current;
                    if(key.IsSigningKey){
                        return key;
                    }
                }
            }

            return null;
        }
		public IEnumerable<PgpSecretKey> EnumerateAllEncryptionSecretKeys()
		{
			using (var inputStream = File.OpenRead(Context.PrivateKeyRingFile))
			using (var decoderStream = PgpUtilities.GetDecoderStream(inputStream))
			{
				var pgpPub = new PgpSecretKeyRingBundle(decoderStream);

				foreach (PgpSecretKeyRing kRing in pgpPub.GetKeyRings())
				{
					foreach (PgpSecretKey k in kRing.GetSecretKeys())
					{
						if (IsEncryptionKey(k.PublicKey))
							yield return k;
					}
				}
			}
		}
		public PgpSecretKey GetMasterSecretKey(long subKeyId)
		{
			using (var inputStream = File.OpenRead(Context.PrivateKeyRingFile))
			using (var decoderStream = PgpUtilities.GetDecoderStream(inputStream))
			{
				var pgpPub = new PgpSecretKeyRingBundle(decoderStream);

				foreach (PgpSecretKeyRing kRing in pgpPub.GetKeyRings())
				{
					var masterKey = kRing.GetSecretKey();
					if(!masterKey.IsMasterKey)
					{
						foreach (PgpSecretKey k in kRing.GetSecretKeys())
						{
							if (k.IsMasterKey)
								masterKey = k;
						}
					}

					foreach (PgpSecretKey k in kRing.GetSecretKeys())
					{
						if (k.KeyId == subKeyId)
							return masterKey;
					}
				}

				return null;
			}
		}
		public PgpSecretKey GetSecretKeyForSigning(string email, out PgpSecretKey masterKey)
		{
			logger.Debug("GetSecretKeyForSigning: {0}", email);
			masterKey = null;

			using (var inputStream = File.OpenRead(Context.PrivateKeyRingFile))
			using (var decoderStream = PgpUtilities.GetDecoderStream(inputStream))
			{
				var pgpPub = new PgpSecretKeyRingBundle(decoderStream);
				var emailSearch = "<" + email.ToLower().Trim() + ">";

				foreach (PgpSecretKeyRing kRing in pgpPub.GetKeyRings())
				{
					masterKey = kRing.GetSecretKey();
					if (!masterKey.IsMasterKey)
						masterKey = GetMasterSecretKey(masterKey.KeyId);

					// Skip key's that don't match
					if (!masterKey.UserIds.Cast<string>().Any(id => id.ToLower().Contains(emailSearch)))
						continue;

					PgpSecretKey signingKey = null;
					foreach (PgpSecretKey k in kRing.GetSecretKeys())
					{
						if (!IsSigningKey(k.PublicKey) || !IsKeyValid(k))
							continue;

						// Prever sub-key over master key
						if (!k.IsMasterKey)
							return k;

						signingKey = k;
					}

					if (signingKey != null)
						return signingKey;
				}

				return null;
			}
		}
		public string[] GetSecretKeyUserIds()
		{
			logger.Debug("GetSecretKeyUserIds");

			using (var inputStream = File.OpenRead(Context.PrivateKeyRingFile))
			using (var decoderStream = PgpUtilities.GetDecoderStream(inputStream))
			{
				var pgpPub = new PgpSecretKeyRingBundle(decoderStream);
				var keyUserIds = new List<string>();

				foreach (PgpSecretKeyRing kRing in pgpPub.GetKeyRings())
				{
					foreach (PgpSecretKey k in kRing.GetSecretKeys())
					{
						var masterKey = k;
						if (!k.IsMasterKey)
							masterKey = GetMasterSecretKey(k.KeyId);

						foreach (string id in masterKey.UserIds)
						{
							if (!keyUserIds.Contains(id))
								keyUserIds.Add(id);
						}
					}
				}

				return keyUserIds.ToArray();
			}
		}
Beispiel #16
0
 /// <summary>
 /// Return the first key we can use to encrypt.
 /// Note: A file can contain multiple keys (stored in "key rings")
 /// </summary>
 private PgpSecretKey GetFirstSecretKey(PgpSecretKeyRingBundle secretKeyRingBundle)
 {
     foreach (PgpSecretKeyRing kRing in secretKeyRingBundle.GetKeyRings())
     {
         PgpSecretKey key = null;
         foreach(PgpSecretKey k in kRing.GetSecretKeys())
         {
             /*.Cast<PgpSecretKey>()
             .Where(k >= k.IsSigningKey)
             .FirstOrDefault();*/
             if (k.IsSigningKey)
             {
                 key = k;
                 break;
             }
         }
         if (key != null)
             return key;
     }
     return null;
 }
Beispiel #17
0
    /// <summary>
    /// Decrypt a PGP message (i.e. "-----BEGIN PGP MESSAGE----- ... -----END PGP MESSAGE-----")
    /// using the supplied private key.
    /// </summary>
    /// <param name="armoredCipher">PGP message to decrypt</param>
    /// <param name="armoredPrivateKey">PGP private key</param>
    /// <param name="keyPassword">PGP private key password or null if none</param>
    /// <returns>decrypted plain text</returns>
    public static string PGPDecrypt(string armoredCipher, string armoredPrivateKey, string keyPassword)
    {
      // decode the private key
      PgpPrivateKey privateKey = null;
      using (MemoryStream ms = new MemoryStream(Encoding.ASCII.GetBytes(armoredPrivateKey)))
      {
        using (Stream dis = PgpUtilities.GetDecoderStream(ms))
        {
          PgpSecretKeyRingBundle bundle = new PgpSecretKeyRingBundle(dis);
          foreach (PgpSecretKeyRing keyring in bundle.GetKeyRings())
          {
            foreach (PgpSecretKey key in keyring.GetSecretKeys())
            {
              privateKey = key.ExtractPrivateKey(keyPassword != null ? keyPassword.ToCharArray() : null);
              break;
            }
          }
        }
      }

      // decrypt armored block using our private key
      byte[] cipher = Encoding.ASCII.GetBytes(armoredCipher);
      using (MemoryStream decryptedStream = new MemoryStream())
      {
        using (MemoryStream inputStream = new MemoryStream(cipher))
        {
          using (ArmoredInputStream ais = new ArmoredInputStream(inputStream))
          {
            PgpObject message = new PgpObjectFactory(ais).NextPgpObject();
            if (message is PgpEncryptedDataList)
            {
              foreach (PgpPublicKeyEncryptedData pked in ((PgpEncryptedDataList)message).GetEncryptedDataObjects())
              {
                message = new PgpObjectFactory(pked.GetDataStream(privateKey)).NextPgpObject();
              }
            }
            if (message is PgpCompressedData)
            {
              message = new PgpObjectFactory(((PgpCompressedData)message).GetDataStream()).NextPgpObject();
            }
            if (message is PgpLiteralData)
            {
              byte[] buffer = new byte[4096];
              using (Stream stream = ((PgpLiteralData)message).GetInputStream())
              {
                int read;
                while ((read = stream.Read(buffer, 0, 4096)) > 0)
                {
                  decryptedStream.Write(buffer, 0, read);
                }
              }
            }

            return Encoding.UTF8.GetString(decryptedStream.ToArray());
          }
        }
      }
		}
        public PgpSecretKey GetSecretKeyForSigning(string email)
        {
            using (var inputStream = File.OpenRead(Context.PrivateKeyRingFile))
            {
                using (var decoderStream = PgpUtilities.GetDecoderStream(inputStream))
                {
                    var pgpPub = new PgpSecretKeyRingBundle(decoderStream);
                    var emailSearch = "<" + email.ToLower().Trim() + ">";

                    foreach (PgpSecretKeyRing kRing in pgpPub.GetKeyRings())
                    {
                        foreach (PgpSecretKey k in kRing.GetSecretKeys())
                        {
                            if (!IsSigningKey(k.PublicKey))
                                continue;

                            if (!k.IsMasterKey)
                            {
                                foreach (PgpSignature sig in k.PublicKey.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.PublicKey.GetUserIds())
                            {
                                if (id.ToLower().IndexOf(emailSearch) > -1)
                                    return k;
                            }
                        }
                    }

                    return null;
                }
            }
        }
        public string[] GetSecretKeyUserIds()
        {
            using (var inputStream = File.OpenRead(Context.PrivateKeyRingFile))
            {
                using (var decoderStream = PgpUtilities.GetDecoderStream(inputStream))
                {
                    var pgpPub = new PgpSecretKeyRingBundle(decoderStream);
                    var keyUserIds = new List<string>();

                    foreach (PgpSecretKeyRing kRing in pgpPub.GetKeyRings())
                    {
                        foreach (PgpSecretKey k in kRing.GetSecretKeys())
                        {
                            if (!k.IsMasterKey)
                            {
                                foreach (PgpSignature sig in k.PublicKey.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.PublicKey.GetUserIds())
                            {
                                if(!keyUserIds.Contains(id))
                                    keyUserIds.Add(id);
                            }
                        }
                    }

                    return keyUserIds.ToArray();
                }
            }
        }
Beispiel #20
0
		private PgpSecretKey readSecretKey(Stream privateKeyStream)
		{
			PgpSecretKeyRingBundle pgpSec;
			try
			{
				pgpSec = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(privateKeyStream));
			}
			catch (Exception e)
			{
				throw new Exception("Invalid private key stream, reason: " + e.Message);
			}
			
			var keyRings = pgpSec.GetKeyRings();
			foreach( PgpSecretKeyRing keyRing in keyRings)
			{
				foreach(PgpSecretKey key in keyRing.GetSecretKeys())
				{
                    if (key.UserIds.Cast<String>().Where(id => id == _userId).Count() > 0)
                    {
                        try
                        {
                            key.ExtractPrivateKey(_passPhrase.ToCharArray());
                            return key;
                        }
                        catch { continue; }
                    }
				}
			}
			
			throw new Exception("Could not find a valid signing key");
		}