/// <summary> /// Attempt to encrypt a message using PGP with the specified public key(s). /// </summary> /// <param name="messageStream">Stream containing the message to encrypt.</param> /// <param name="fileName">File name of for the message.</param> /// <param name="signedAndEncryptedMessageStream">Stream to write the encrypted message into.</param> /// <param name="senderPublicKey">The BouncyCastle public key associated with the signature.</param> /// <param name="senderPrivateKey">The BouncyCastle private key to be used for signing.</param> /// <param name="recipientPublicKeys">Collection of BouncyCastle public keys to be used for encryption.</param> /// <param name="hashAlgorithmTag">The hash algorithm tag to use for signing.</param> /// <param name="symmetricKeyAlgorithmTag">The symmetric key algorithm tag to use for encryption.</param> /// <param name="armor">Whether to wrap the message with ASCII armor.</param> /// <returns>Whether the encryption completed successfully.</returns> public static bool SignAndEncrypt(Stream messageStream, string fileName, Stream signedAndEncryptedMessageStream, PgpPublicKey senderPublicKey, PgpPrivateKey senderPrivateKey, IEnumerable<PgpPublicKey> recipientPublicKeys, HashAlgorithmTag hashAlgorithmTag = HashAlgorithmTag.Sha256, SymmetricKeyAlgorithmTag symmetricKeyAlgorithmTag = SymmetricKeyAlgorithmTag.TripleDes, bool armor = true) { // Create a signature generator. PgpSignatureGenerator signatureGenerator = new PgpSignatureGenerator(senderPublicKey.Algorithm, hashAlgorithmTag); signatureGenerator.InitSign(PgpSignature.BinaryDocument, senderPrivateKey); // Add the public key user ID. foreach (string userId in senderPublicKey.GetUserIds()) { PgpSignatureSubpacketGenerator signatureSubGenerator = new PgpSignatureSubpacketGenerator(); signatureSubGenerator.SetSignerUserId(false, userId); signatureGenerator.SetHashedSubpackets(signatureSubGenerator.Generate()); break; } // Allow any of the corresponding keys to be used for decryption. PgpEncryptedDataGenerator encryptedDataGenerator = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.TripleDes, true, new SecureRandom()); foreach (PgpPublicKey publicKey in recipientPublicKeys) { encryptedDataGenerator.AddMethod(publicKey); } // Handle optional ASCII armor. if (armor) { using (Stream armoredStream = new ArmoredOutputStream(signedAndEncryptedMessageStream)) { using (Stream encryptedStream = encryptedDataGenerator.Open(armoredStream, new byte[Constants.LARGEBUFFERSIZE])) { PgpCompressedDataGenerator compressedDataGenerator = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Uncompressed); using (Stream compressedStream = compressedDataGenerator.Open(encryptedStream)) { signatureGenerator.GenerateOnePassVersion(false).Encode(compressedStream); PgpLiteralDataGenerator literalDataGenerator = new PgpLiteralDataGenerator(); using (Stream literalStream = literalDataGenerator.Open(compressedStream, PgpLiteralData.Binary, fileName, DateTime.Now, new byte[Constants.LARGEBUFFERSIZE])) { // Process each character in the message. int messageChar; while ((messageChar = messageStream.ReadByte()) >= 0) { literalStream.WriteByte((byte)messageChar); signatureGenerator.Update((byte)messageChar); } } signatureGenerator.Generate().Encode(compressedStream); } } } } else { using (Stream encryptedStream = encryptedDataGenerator.Open(signedAndEncryptedMessageStream, new byte[Constants.LARGEBUFFERSIZE])) { PgpCompressedDataGenerator compressedDataGenerator = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Uncompressed); using (Stream compressedStream = compressedDataGenerator.Open(encryptedStream)) { signatureGenerator.GenerateOnePassVersion(false).Encode(compressedStream); PgpLiteralDataGenerator literalDataGenerator = new PgpLiteralDataGenerator(); using (Stream literalStream = literalDataGenerator.Open(compressedStream, PgpLiteralData.Binary, fileName, DateTime.Now, new byte[Constants.LARGEBUFFERSIZE])) { // Process each character in the message. int messageChar; while ((messageChar = messageStream.ReadByte()) >= 0) { literalStream.WriteByte((byte)messageChar); signatureGenerator.Update((byte)messageChar); } } signatureGenerator.Generate().Encode(compressedStream); } } } return true; }
internal OpenPgpDigitalCertificate (PgpPublicKey pubkey) { var data = pubkey.GetFingerprint (); var builder = new StringBuilder (); for (int i = 0; i < data.Length; i++) builder.Append (data[i].ToString ("X")); // var trust = pubkey.GetTrustData (); // if (trust != null) { // TrustLevel = (TrustLevel) (trust[0] & 15); // } else { // TrustLevel = TrustLevel.None; // } Fingerprint = builder.ToString (); PublicKey = pubkey; foreach (string userId in pubkey.GetUserIds ()) { data = Encoding.UTF8.GetBytes (userId); MailboxAddress mailbox; int index = 0; if (!MailboxAddress.TryParse (ParserOptions.Default, data, ref index, data.Length, false, out mailbox)) continue; Email = mailbox.Address; Name = mailbox.Name; break; } }
/// <summary>Remove a certification from the key.</summary> /// <param name="key">The key the certifications are to be removed from.</param> /// <param name="certification">The certfication to be removed.</param> /// <returns>The modified key, null if the certification was not found.</returns> public static PgpPublicKey RemoveCertification( PgpPublicKey key, PgpSignature certification) { PgpPublicKey returnKey = new PgpPublicKey(key); IList sigs = returnKey.subSigs != null ? returnKey.subSigs : returnKey.keySigs; // bool found = sigs.Remove(certification); int pos = sigs.IndexOf(certification); bool found = pos >= 0; if (found) { sigs.RemoveAt(pos); } else { foreach (String id in key.GetUserIds()) { foreach (object sig in key.GetSignaturesForId(id)) { // TODO Is this the right type of equality test? if (certification == sig) { found = true; returnKey = PgpPublicKey.RemoveCertification(returnKey, id, certification); } } } if (!found) { foreach (PgpUserAttributeSubpacketVector id in key.GetUserAttributes()) { foreach (object sig in key.GetSignaturesForUserAttribute(id)) { // TODO Is this the right type of equality test? if (certification == sig) { found = true; returnKey = PgpPublicKey.RemoveCertification(returnKey, id, certification); } } } } } return(returnKey); }
/// <summary>Remove a certification from the key.</summary> /// <param name="key">The key the certifications are to be removed from.</param> /// <param name="certification">The certfication to be removed.</param> /// <returns>The modified key, null if the certification was not found.</returns> public static PgpPublicKey RemoveCertification(PgpPublicKey key, PgpSignature certification) { var returnKey = new PgpPublicKey(key); var sigs = returnKey.SubSigs ?? returnKey.KeySigs; // bool found = sigs.Remove(certification); var pos = sigs.IndexOf(certification); var found = pos >= 0; if (found) { sigs.RemoveAt(pos); } else { foreach (string id in key.GetUserIds()) { foreach (var sig in key.GetSignaturesForId(id)) { // TODO Is this the right type of equality test? if (certification != sig) { continue; } found = true; returnKey = PgpPublicKey.RemoveCertification(returnKey, id, certification); } } if (!found) { foreach (IPgpUserAttributeSubpacketVector id in key.GetUserAttributes()) { foreach (var sig in key.GetSignaturesForUserAttribute(id)) { // TODO Is this the right type of equality test? if (certification != sig) { continue; } // found = true; returnKey = PgpPublicKey.RemoveCertification(returnKey, id, certification); } } } } return(returnKey); }
/// <summary>Remove a certification from the key.</summary> /// <param name="key">The key the certifications are to be removed from.</param> /// <param name="certification">The certfication to be removed.</param> /// <returns>The modified key, null if the certification was not found.</returns> public static PgpPublicKey RemoveCertification(PgpPublicKey key, PgpSignature certification) { var returnKey = new PgpPublicKey(key); var sigs = returnKey.SubSigs ?? returnKey.KeySigs; // bool found = sigs.Remove(certification); var pos = sigs.IndexOf(certification); var found = pos >= 0; if (found) { sigs.RemoveAt(pos); } else { foreach (string id in key.GetUserIds()) { foreach (var sig in key.GetSignaturesForId(id)) { // TODO Is this the right type of equality test? if (certification != sig) continue; found = true; returnKey = PgpPublicKey.RemoveCertification(returnKey, id, certification); } } if (!found) { foreach (IPgpUserAttributeSubpacketVector id in key.GetUserAttributes()) { foreach (var sig in key.GetSignaturesForUserAttribute(id)) { // TODO Is this the right type of equality test? if (certification != sig) continue; // found = true; returnKey = PgpPublicKey.RemoveCertification(returnKey, id, certification); } } } } return returnKey; }
/// <summary>Remove a certification from the key.</summary> /// <param name="key">The key the certifications are to be removed from.</param> /// <param name="certification">The certfication to be removed.</param> /// <returns>The modified key, null if the certification was not found.</returns> public static PgpPublicKey RemoveCertification( PgpPublicKey key, PgpSignature certification) { PgpPublicKey returnKey = new PgpPublicKey(key); IList sigs = returnKey.subSigs != null ? returnKey.subSigs : returnKey.keySigs; // bool found = sigs.Remove(certification); int pos = sigs.IndexOf(certification); bool found = pos >= 0; if (found) { sigs.RemoveAt(pos); } else { foreach (String id in key.GetUserIds()) { foreach (object sig in key.GetSignaturesForId(id)) { // TODO Is this the right type of equality test? if (certification == sig) { found = true; returnKey = PgpPublicKey.RemoveCertification(returnKey, id, certification); } } } if (!found) { foreach (PgpUserAttributeSubpacketVector id in key.GetUserAttributes()) { foreach (object sig in key.GetSignaturesForUserAttribute(id)) { // TODO Is this the right type of equality test? if (certification == sig) { found = true; returnKey = PgpPublicKey.RemoveCertification(returnKey, id, certification); } } } } } return returnKey; }
/// <summary> /// Attempt to sign a PGP message using the specific private key. /// </summary> /// <param name="messageStream">Stream containing the message to sign.</param> /// <param name="signatureStream">Stream to write the signature into.</param> /// <param name="senderPublicKey">The BouncyCastle public key associated with the signature.</param> /// <param name="senderPrivateKey">The BouncyCastle private key to be used for signing.</param> /// <param name="hashAlgorithmTag">The hash algorithm tag to use for signing.</param> /// <param name="armor">Whether to wrap the message with ASCII armor.</param> /// <returns>Whether the signature completed successfully.</returns> public static bool Sign(Stream messageStream, Stream signatureStream, PgpPublicKey senderPublicKey, PgpPrivateKey senderPrivateKey, HashAlgorithmTag hashAlgorithmTag = HashAlgorithmTag.Sha256, bool armor = true) { // Create a signature generator. PgpSignatureGenerator signatureGenerator = new PgpSignatureGenerator(senderPublicKey.Algorithm, hashAlgorithmTag); signatureGenerator.InitSign(PgpSignature.BinaryDocument, senderPrivateKey); // Add the public key user ID. foreach (string userId in senderPublicKey.GetUserIds()) { PgpSignatureSubpacketGenerator signatureSubGenerator = new PgpSignatureSubpacketGenerator(); signatureSubGenerator.SetSignerUserId(false, userId); signatureGenerator.SetHashedSubpackets(signatureSubGenerator.Generate()); break; } // Handle ASCII armor. if (armor) { using (ArmoredOutputStream armoredStream = new ArmoredOutputStream(signatureStream)) { armoredStream.BeginClearText(hashAlgorithmTag); // Process each character in the message. int messageChar; while ((messageChar = messageStream.ReadByte()) >= 0) { armoredStream.WriteByte((byte)messageChar); signatureGenerator.Update((byte)messageChar); } armoredStream.EndClearText(); using (BcpgOutputStream bcpgStream = new BcpgOutputStream(armoredStream)) { signatureGenerator.Generate().Encode(bcpgStream); } } } else { // Process each character in the message. int messageChar; while ((messageChar = messageStream.ReadByte()) >= 0) { signatureGenerator.Update((byte)messageChar); } signatureGenerator.Generate().Encode(signatureStream); } return true; }
static bool PgpPublicKeyMatches (PgpPublicKey key, MailboxAddress mailbox) { var secure = mailbox as SecureMailboxAddress; if (secure != null) { var fingerprint = GetFingerprint (key.KeyId, secure.Fingerprint.Length); return secure.Fingerprint.EndsWith (fingerprint, StringComparison.OrdinalIgnoreCase); } foreach (string userId in key.GetUserIds ()) { MailboxAddress email; if (!MailboxAddress.TryParse (userId, out email)) continue; if (string.Compare (mailbox.Address, email.Address, StringComparison.OrdinalIgnoreCase) == 0) return true; } return false; }
static bool PgpPublicKeyMatches (PgpPublicKey key, MailboxAddress mailbox) { var secure = mailbox as SecureMailboxAddress; if (secure != null && !string.IsNullOrEmpty (secure.Fingerprint)) { if (secure.Fingerprint.Length > 16) { var fingerprint = HexEncode (key.GetFingerprint ()); return secure.Fingerprint.Equals (fingerprint, StringComparison.OrdinalIgnoreCase); } else { var id = ((int) key.KeyId).ToString ("X2"); return secure.Fingerprint.EndsWith (id, StringComparison.OrdinalIgnoreCase); } } foreach (string userId in key.GetUserIds ()) { MailboxAddress email; if (!MailboxAddress.TryParse (userId, out email)) continue; if (mailbox.Address.Equals (email.Address, StringComparison.OrdinalIgnoreCase)) return true; } return false; }
static bool PgpPublicKeyMatches(PgpPublicKey key, MailboxAddress mailbox) { foreach (string userId in key.GetUserIds ()) { MailboxAddress email; if (!MailboxAddress.TryParse (userId, out email)) continue; if (string.Compare (mailbox.Address, email.Address, StringComparison.OrdinalIgnoreCase) == 0) return true; } return false; }
public static PgpPublicKey RemoveCertification(PgpPublicKey key, PgpSignature certification) { PgpPublicKey pgpPublicKey = new PgpPublicKey(key); global::System.Collections.IList list = ((pgpPublicKey.subSigs != null) ? pgpPublicKey.subSigs : pgpPublicKey.keySigs); int num = list.IndexOf((object)certification); bool flag = num >= 0; if (flag) { list.RemoveAt(num); } else { { global::System.Collections.IEnumerator enumerator = key.GetUserIds().GetEnumerator(); try { while (enumerator.MoveNext()) { string id = (string)enumerator.get_Current(); { global::System.Collections.IEnumerator enumerator2 = key.GetSignaturesForId(id).GetEnumerator(); try { while (enumerator2.MoveNext()) { object current = enumerator2.get_Current(); if (certification == current) { flag = true; pgpPublicKey = RemoveCertification(pgpPublicKey, id, certification); } } } finally { global::System.IDisposable disposable2 = enumerator2 as global::System.IDisposable; if (disposable2 != null) { disposable2.Dispose(); } } } } } finally { global::System.IDisposable disposable = enumerator as global::System.IDisposable; if (disposable != null) { disposable.Dispose(); } } } if (!flag) { global::System.Collections.IEnumerator enumerator = key.GetUserAttributes().GetEnumerator(); try { while (enumerator.MoveNext()) { PgpUserAttributeSubpacketVector userAttributes = (PgpUserAttributeSubpacketVector)enumerator.get_Current(); { global::System.Collections.IEnumerator enumerator2 = key.GetSignaturesForUserAttribute(userAttributes).GetEnumerator(); try { while (enumerator2.MoveNext()) { object current2 = enumerator2.get_Current(); if (certification == current2) { flag = true; pgpPublicKey = RemoveCertification(pgpPublicKey, userAttributes, certification); } } } finally { global::System.IDisposable disposable4 = enumerator2 as global::System.IDisposable; if (disposable4 != null) { disposable4.Dispose(); } } } } return(pgpPublicKey); } finally { global::System.IDisposable disposable3 = enumerator as global::System.IDisposable; if (disposable3 != null) { disposable3.Dispose(); } } } } return(pgpPublicKey); }
private void Load(PgpPublicKey key) { this.KeyId = key.KeyId.ToString("X"); if (this.KeyId != null && this.KeyId.Length >= 15) { this.KeyIdShort = this.KeyId.Substring(this.KeyId.Length - 8); } this.Algorithm = key.Algorithm.ToString(); this.BitStrength = key.BitStrength; this.IsMasterKey = key.IsMasterKey; this.IsEncryptionKey = key.IsEncryptionKey; this.Version = key.Version; this.CreatedOnUtc = key.CreationTime.ToUniversalTime(); var validForSeconds = key.GetValidSeconds(); if(validForSeconds > 0) { this.Expires = this.CreatedOnUtc.Value.AddSeconds(validForSeconds); } //this.ValidDays = key.ValidDays; //if (this.ValidDays.HasValue) //{ // this.Expires = this.CreatedOnUtc.Value.AddDays(this.ValidDays.Value); //} //else //{ // this.Expires = null; //} try { var userIds = key.GetUserIds(); if (userIds != null) { var enumerator = userIds.GetEnumerator(); if (enumerator.MoveNext()) { var userIdentity = enumerator.Current as string; if (userIdentity != null && userIdentity.Contains("<") && userIdentity.Contains(">")) { var name = userIdentity.Substring(0, userIdentity.IndexOf("<") - 1).Trim(); this.IdentityName = name; var email = userIdentity.Substring(userIdentity.IndexOf("<") + 1); email = email.Substring(0, email.IndexOf(">")).Trim(); this.IdentityEmail = email; } } } } catch { } }