本文整理汇总了C#中Org.BouncyCastle.Bcpg.OpenPgp.PgpSecretKey类的典型用法代码示例。如果您正苦于以下问题:C# PgpSecretKey类的具体用法?C# PgpSecretKey怎么用?C# PgpSecretKey使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
PgpSecretKey类属于Org.BouncyCastle.Bcpg.OpenPgp命名空间,在下文中一共展示了PgpSecretKey类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ExportKeyPair
private static void ExportKeyPair(
Stream secretOut,
Stream publicOut,
AsymmetricKeyParameter publicKey,
AsymmetricKeyParameter privateKey,
string identity,
char[] passPhrase,
bool armor)
{
if (armor)
{
secretOut = new ArmoredOutputStream(secretOut);
}
PgpSecretKey secretKey = new PgpSecretKey(
PgpSignature.DefaultCertification,
PublicKeyAlgorithmTag.RsaGeneral,
publicKey,
privateKey,
DateTime.UtcNow,
identity,
SymmetricKeyAlgorithmTag.Cast5,
passPhrase,
null,
null,
new SecureRandom()
);
secretKey.Encode(secretOut);
if (armor)
{
secretOut.Close();
publicOut = new ArmoredOutputStream(publicOut);
}
PgpPublicKey key = secretKey.PublicKey;
key.Encode(publicOut);
if (armor)
{
publicOut.Close();
}
}
示例2: FormPassphrase
internal FormPassphrase(PgpSecretKey masterKey, PgpSecretKey key)
{
TopMost = true;
InitializeComponent();
var userIds = masterKey.UserIds.GetEnumerator();
userIds.MoveNext();
var userId = userIds.Current.ToString();
var strength = key.PublicKey.BitStrength.ToString();
var createDate = key.PublicKey.CreationTime.ToShortDateString();
var alg = key.PublicKey.Algorithm.ToString().Replace("Algorithm", "");
var fingerPrint = key.PublicKey.GetFingerprint();
var fingerPrintLength = fingerPrint.Length;
var keyId =
fingerPrint[fingerPrintLength - 4].ToString("X2") +
fingerPrint[fingerPrintLength - 3].ToString("X2") +
fingerPrint[fingerPrintLength - 2].ToString("X2") +
fingerPrint[fingerPrintLength - 1].ToString("X2");
labelKeyInfo.Text = string.Format("\"{0}\"\n{1}-{2} key, ID {3}\n{4}",
userId, strength, alg, keyId, createDate);
}
示例3: Create
/// <summary>
/// Creates a new <see cref="MultipartEncrypted"/>.
/// </summary>
/// <remarks>
/// Signs the entity using the supplied signer and digest algorithm and then encrypts to
/// the specified recipients, encapsulating the result in a new multipart/encrypted part.
/// </remarks>
/// <returns>A new <see cref="MimeKit.Cryptography.MultipartEncrypted"/> instance containing
/// the signed and encrypted version of the specified entity.</returns>
/// <param name="ctx">The OpenPGP cryptography context to use for singing and encrypting.</param>
/// <param name="signer">The signer to use to sign the entity.</param>
/// <param name="digestAlgo">The digest algorithm to use for signing.</param>
/// <param name="recipients">The recipients for the encrypted entity.</param>
/// <param name="entity">The entity to sign and encrypt.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="ctx"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="signer"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="recipients"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="entity"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentException">
/// <para><paramref name="signer"/> cannot be used for signing.</para>
/// <para>-or-</para>
/// <para>One or more of the recipient keys cannot be used for encrypting.</para>
/// <para>-or-</para>
/// <para>No recipients were specified.</para>
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// The <paramref name="digestAlgo"/> was out of range.
/// </exception>
/// <exception cref="System.NotSupportedException">
/// The <paramref name="digestAlgo"/> is not supported.
/// </exception>
/// <exception cref="System.OperationCanceledException">
/// The user chose to cancel the password prompt.
/// </exception>
/// <exception cref="System.UnauthorizedAccessException">
/// 3 bad attempts were made to unlock the secret key.
/// </exception>
public static MultipartEncrypted Create (OpenPgpContext ctx, PgpSecretKey signer, DigestAlgorithm digestAlgo, IEnumerable<PgpPublicKey> recipients, MimeEntity entity)
{
if (ctx == null)
throw new ArgumentNullException ("ctx");
if (signer == null)
throw new ArgumentNullException ("signer");
if (recipients == null)
throw new ArgumentNullException ("recipients");
if (entity == null)
throw new ArgumentNullException ("entity");
using (var memory = new MemoryStream ()) {
var options = FormatOptions.Default.Clone ();
options.NewLineFormat = NewLineFormat.Dos;
PrepareEntityForEncrypting (entity);
entity.WriteTo (options, memory);
memory.Position = 0;
var encrypted = new MultipartEncrypted ();
encrypted.ContentType.Parameters["protocol"] = ctx.EncryptionProtocol;
// add the protocol version part
encrypted.Add (new ApplicationPgpEncrypted ());
// add the encrypted entity as the second part
encrypted.Add (ctx.SignAndEncrypt (signer, digestAlgo, recipients, memory));
return encrypted;
}
}
示例4: Sign
/// <summary>
/// Cryptographically signs the content.
/// </summary>
/// <remarks>
/// Cryptographically signs the content using the specified signer and digest algorithm.
/// </remarks>
/// <returns>A new <see cref="MimeKit.MimePart"/> instance
/// containing the detached signature data.</returns>
/// <param name="signer">The signer.</param>
/// <param name="digestAlgo">The digest algorithm to use for signing.</param>
/// <param name="content">The content.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="signer"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="content"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentException">
/// <paramref name="signer"/> cannot be used for signing.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// The <paramref name="digestAlgo"/> was out of range.
/// </exception>
/// <exception cref="System.NotSupportedException">
/// The <paramref name="digestAlgo"/> is not supported.
/// </exception>
/// <exception cref="System.OperationCanceledException">
/// The user chose to cancel the password prompt.
/// </exception>
/// <exception cref="System.UnauthorizedAccessException">
/// 3 bad attempts were made to unlock the secret key.
/// </exception>
public ApplicationPgpSignature Sign (PgpSecretKey signer, DigestAlgorithm digestAlgo, Stream content)
{
if (signer == null)
throw new ArgumentNullException ("signer");
if (!signer.IsSigningKey)
throw new ArgumentException ("The specified secret key cannot be used for signing.", "signer");
if (content == null)
throw new ArgumentNullException ("content");
var hashAlgorithm = GetHashAlgorithm (digestAlgo);
var memory = new MemoryBlockStream ();
using (var armored = new ArmoredOutputStream (memory)) {
var compresser = new PgpCompressedDataGenerator (CompressionAlgorithmTag.ZLib);
using (var compressed = compresser.Open (armored)) {
var signatureGenerator = new PgpSignatureGenerator (signer.PublicKey.Algorithm, hashAlgorithm);
var buf = new byte[4096];
int nread;
signatureGenerator.InitSign (PgpSignature.CanonicalTextDocument, GetPrivateKey (signer));
while ((nread = content.Read (buf, 0, buf.Length)) > 0)
signatureGenerator.Update (buf, 0, nread);
var signature = signatureGenerator.Generate ();
signature.Encode (compressed);
compressed.Flush ();
}
armored.Flush ();
}
memory.Position = 0;
return new ApplicationPgpSignature (memory);
}
示例5: PGPGenerateKey
/// <summary>
/// Build a PGP key pair
/// </summary>
/// <param name="bits">number of bits in key, e.g. 2048</param>
/// <param name="identifier">key identifier, e.g. "Your Name <[email protected]>" </param>
/// <param name="password">key password or null</param>
/// <param name="privateKey">returned ascii private key</param>
/// <param name="publicKey">returned ascii public key</param>
public static void PGPGenerateKey(int bits, string identifier, string password, out string privateKey, out string publicKey)
{
// generate a new RSA keypair
RsaKeyPairGenerator gen = new RsaKeyPairGenerator();
gen.Init(new RsaKeyGenerationParameters(BigInteger.ValueOf(0x101), new Org.BouncyCastle.Security.SecureRandom(), bits, 80));
AsymmetricCipherKeyPair pair = gen.GenerateKeyPair();
// create PGP subpacket
PgpSignatureSubpacketGenerator hashedGen = new PgpSignatureSubpacketGenerator();
hashedGen.SetKeyFlags(true, PgpKeyFlags.CanCertify | PgpKeyFlags.CanSign | PgpKeyFlags.CanEncryptCommunications | PgpKeyFlags.CanEncryptStorage);
hashedGen.SetPreferredCompressionAlgorithms(false, new int[] { (int)CompressionAlgorithmTag.Zip });
hashedGen.SetPreferredHashAlgorithms(false, new int[] { (int)HashAlgorithmTag.Sha1 });
hashedGen.SetPreferredSymmetricAlgorithms(false, new int[] { (int)SymmetricKeyAlgorithmTag.Cast5 });
PgpSignatureSubpacketVector sv = hashedGen.Generate();
PgpSignatureSubpacketGenerator unhashedGen = new PgpSignatureSubpacketGenerator();
// create the PGP key
PgpSecretKey secretKey = new PgpSecretKey(
PgpSignature.DefaultCertification,
PublicKeyAlgorithmTag.RsaGeneral,
pair.Public,
pair.Private,
DateTime.Now,
identifier,
SymmetricKeyAlgorithmTag.Cast5,
(password != null ? password.ToCharArray() : null),
hashedGen.Generate(),
unhashedGen.Generate(),
new Org.BouncyCastle.Security.SecureRandom());
// extract the keys
using (MemoryStream ms = new MemoryStream())
{
using (ArmoredOutputStream ars = new ArmoredOutputStream(ms))
{
secretKey.Encode(ars);
}
privateKey = Encoding.ASCII.GetString(ms.ToArray());
}
using (MemoryStream ms = new MemoryStream())
{
using (ArmoredOutputStream ars = new ArmoredOutputStream(ms))
{
secretKey.PublicKey.Encode(ars);
}
publicKey = Encoding.ASCII.GetString(ms.ToArray());
}
}
示例6: Create
/// <summary>
/// Creates a new <see cref="MultipartSigned"/>.
/// </summary>
/// <remarks>
/// Cryptographically signs the entity using the supplied signer and digest algorithm in
/// order to generate a detached signature and then adds the entity along with the
/// detached signature data to a new multipart/signed part.
/// </remarks>
/// <returns>A new <see cref="MultipartSigned"/> instance.</returns>
/// <param name="signer">The signer.</param>
/// <param name="digestAlgo">The digest algorithm to use for signing.</param>
/// <param name="entity">The entity to sign.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="signer"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="entity"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentException">
/// <paramref name="signer"/> cannot be used for signing.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// The <paramref name="digestAlgo"/> was out of range.
/// </exception>
/// <exception cref="System.NotSupportedException">
/// <para>A cryptography context suitable for signing could not be found.</para>
/// <para>-or-</para>
/// <para>The <paramref name="digestAlgo"/> is not supported.</para>
/// </exception>
/// <exception cref="Org.BouncyCastle.Bcpg.OpenPgp.PgpException">
/// An error occurred in the OpenPGP subsystem.
/// </exception>
public static MultipartSigned Create (PgpSecretKey signer, DigestAlgorithm digestAlgo, MimeEntity entity)
{
using (var ctx = (OpenPgpContext) CryptographyContext.Create ("application/pgp-signature")) {
return Create (ctx, signer, digestAlgo, entity);
}
}
示例7: PgpSecretKeyMatches
static bool PgpSecretKeyMatches(PgpSecretKey key, MailboxAddress mailbox)
{
foreach (string userId in key.UserIds) {
MailboxAddress email;
if (!MailboxAddress.TryParse (userId, out email))
continue;
if (string.Compare (mailbox.Address, email.Address, StringComparison.OrdinalIgnoreCase) == 0)
return true;
}
return false;
}
示例8: InsertSecretKey
/// <summary>
/// Returns a new key ring with the secret key passed in either added or
/// replacing an existing one with the same key ID.
/// </summary>
/// <param name="secRing">The secret key ring to be modified.</param>
/// <param name="secKey">The secret key to be inserted.</param>
/// <returns>A new <c>PgpSecretKeyRing</c></returns>
public static PgpSecretKeyRing InsertSecretKey(
PgpSecretKeyRing secRing,
PgpSecretKey secKey)
{
IList keys = Platform.CreateArrayList(secRing.keys);
bool found = false;
bool masterFound = false;
for (int i = 0; i != keys.Count; i++)
{
PgpSecretKey key = (PgpSecretKey) keys[i];
if (key.KeyId == secKey.KeyId)
{
found = true;
keys[i] = secKey;
}
if (key.IsMasterKey)
{
masterFound = true;
}
}
if (!found)
{
if (secKey.IsMasterKey)
{
if (masterFound)
throw new ArgumentException("cannot add a master key to a ring that already has one");
keys.Insert(0, secKey);
}
else
{
keys.Add(secKey);
}
}
return new PgpSecretKeyRing(keys, secRing.extraPubKeys);
}
示例9: GetPasswordForKey
protected override string GetPasswordForKey(PgpSecretKey key)
{
return "no.secret";
}
示例10: CopyWithNewPasswordUtf8
/// <summary>
/// Return a copy of the passed in secret key, encrypted using a new password
/// and the passed in algorithm.
/// </summary>
/// <remarks>
/// The passphrase is encoded to bytes using UTF8 (Encoding.UTF8.GetBytes).
/// </remarks>
/// <param name="key">The PgpSecretKey to be copied.</param>
/// <param name="oldPassPhrase">The current password for the key.</param>
/// <param name="newPassPhrase">The new password for the key.</param>
/// <param name="newEncAlgorithm">The algorithm to be used for the encryption.</param>
/// <param name="rand">Source of randomness.</param>
public static PgpSecretKey CopyWithNewPasswordUtf8(
PgpSecretKey key,
char[] oldPassPhrase,
char[] newPassPhrase,
SymmetricKeyAlgorithmTag newEncAlgorithm,
SecureRandom rand)
{
return DoCopyWithNewPassword(key, PgpUtilities.EncodePassPhrase(oldPassPhrase, true),
PgpUtilities.EncodePassPhrase(newPassPhrase, true), true, newEncAlgorithm, rand);
}
示例11: Create
public static MultipartEncrypted Create (PgpSecretKey signer, DigestAlgorithm digestAlgo, IEnumerable<PgpPublicKey> recipients, MimeEntity entity)
{
return SignAndEncrypt (signer, digestAlgo, recipients, entity);
}
示例12: PgpSecretKeyMatches
static bool PgpSecretKeyMatches (PgpSecretKey key, MailboxAddress mailbox)
{
var secure = mailbox as SecureMailboxAddress;
if (secure != null && !string.IsNullOrEmpty (secure.Fingerprint)) {
if (secure.Fingerprint.Length > 16) {
var fingerprint = HexEncode (key.PublicKey.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.UserIds) {
MailboxAddress email;
if (!MailboxAddress.TryParse (userId, out email))
continue;
if (mailbox.Address.Equals (email.Address, StringComparison.OrdinalIgnoreCase))
return true;
}
return false;
}
示例13: GetPrivateKey
/// <summary>
/// Gets the private key from the specified secret key.
/// </summary>
/// <returns>The private key.</returns>
/// <param name="key">The secret key.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="key"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.OperationCanceledException">
/// The user chose to cancel the password prompt.
/// </exception>
/// <exception cref="System.UnauthorizedAccessException">
/// 3 bad attempts were made to unlock the secret key.
/// </exception>
protected PgpPrivateKey GetPrivateKey(PgpSecretKey key)
{
int attempts = 0;
string password;
if (key == null)
throw new ArgumentNullException ("key");
do {
if ((password = GetPasswordForKey (key)) == null)
throw new OperationCanceledException ();
try {
return key.ExtractPrivateKey (password.ToCharArray ());
} catch (Exception ex) {
Debug.WriteLine ("Failed to extract secret key: {0}", ex);
}
attempts++;
} while (attempts < 3);
throw new UnauthorizedAccessException ();
}
示例14: CopyWithNewPassword
/// <summary>
/// Return a copy of the passed in secret key, encrypted using a new password
/// and the passed in algorithm.
/// </summary>
/// <param name="key">The PgpSecretKey to be copied.</param>
/// <param name="oldPassPhrase">The current password for the key.</param>
/// <param name="newPassPhrase">The new password for the key.</param>
/// <param name="newEncAlgorithm">The algorithm to be used for the encryption.</param>
/// <param name="rand">Source of randomness.</param>
public static PgpSecretKey CopyWithNewPassword(
PgpSecretKey key,
char[] oldPassPhrase,
char[] newPassPhrase,
SymmetricKeyAlgorithmTag newEncAlgorithm,
SecureRandom rand)
{
byte[] rawKeyData = key.ExtractKeyData(oldPassPhrase);
int s2kUsage = key.secret.S2kUsage;
byte[] iv = null;
S2k s2k = null;
byte[] keyData;
if (newEncAlgorithm == SymmetricKeyAlgorithmTag.Null)
{
s2kUsage = SecretKeyPacket.UsageNone;
if (key.secret.S2kUsage == SecretKeyPacket.UsageSha1) // SHA-1 hash, need to rewrite Checksum
{
keyData = new byte[rawKeyData.Length - 18];
Array.Copy(rawKeyData, 0, keyData, 0, keyData.Length - 2);
byte[] check = Checksum(false, keyData, keyData.Length - 2);
keyData[keyData.Length - 2] = check[0];
keyData[keyData.Length - 1] = check[1];
}
else
{
keyData = rawKeyData;
}
}
else
{
try
{
keyData = EncryptKeyData(rawKeyData, newEncAlgorithm, newPassPhrase, rand, out s2k, out iv);
}
catch (PgpException e)
{
throw e;
}
catch (Exception e)
{
throw new PgpException("Exception encrypting key", e);
}
}
SecretKeyPacket secret;
if (key.secret is SecretSubkeyPacket)
{
secret = new SecretSubkeyPacket(key.secret.PublicKeyPacket,
newEncAlgorithm, s2kUsage, s2k, iv, keyData);
}
else
{
secret = new SecretKeyPacket(key.secret.PublicKeyPacket,
newEncAlgorithm, s2kUsage, s2k, iv, keyData);
}
return new PgpSecretKey(secret, key.pub);
}
示例15: DoCopyWithNewPassword
internal static PgpSecretKey DoCopyWithNewPassword(
PgpSecretKey key,
byte[] rawOldPassPhrase,
byte[] rawNewPassPhrase,
bool clearPassPhrase,
SymmetricKeyAlgorithmTag newEncAlgorithm,
SecureRandom rand)
{
if (key.IsPrivateKeyEmpty)
throw new PgpException("no private key in this SecretKey - public key present only.");
byte[] rawKeyData = key.ExtractKeyData(rawOldPassPhrase, clearPassPhrase);
int s2kUsage = key.secret.S2kUsage;
byte[] iv = null;
S2k s2k = null;
byte[] keyData;
PublicKeyPacket pubKeyPacket = key.secret.PublicKeyPacket;
if (newEncAlgorithm == SymmetricKeyAlgorithmTag.Null)
{
s2kUsage = SecretKeyPacket.UsageNone;
if (key.secret.S2kUsage == SecretKeyPacket.UsageSha1) // SHA-1 hash, need to rewrite Checksum
{
keyData = new byte[rawKeyData.Length - 18];
Array.Copy(rawKeyData, 0, keyData, 0, keyData.Length - 2);
byte[] check = Checksum(false, keyData, keyData.Length - 2);
keyData[keyData.Length - 2] = check[0];
keyData[keyData.Length - 1] = check[1];
}
else
{
keyData = rawKeyData;
}
}
else
{
if (s2kUsage == SecretKeyPacket.UsageNone)
{
s2kUsage = SecretKeyPacket.UsageChecksum;
}
try
{
if (pubKeyPacket.Version >= 4)
{
keyData = EncryptKeyDataV4(rawKeyData, newEncAlgorithm, HashAlgorithmTag.Sha1, rawNewPassPhrase, clearPassPhrase, rand, out s2k, out iv);
}
else
{
keyData = EncryptKeyDataV3(rawKeyData, newEncAlgorithm, rawNewPassPhrase, clearPassPhrase, rand, out s2k, out iv);
}
}
catch (PgpException e)
{
throw e;
}
catch (Exception e)
{
throw new PgpException("Exception encrypting key", e);
}
}
SecretKeyPacket secret;
if (key.secret is SecretSubkeyPacket)
{
secret = new SecretSubkeyPacket(pubKeyPacket, newEncAlgorithm, s2kUsage, s2k, iv, keyData);
}
else
{
secret = new SecretKeyPacket(pubKeyPacket, newEncAlgorithm, s2kUsage, s2k, iv, keyData);
}
return new PgpSecretKey(secret, key.pub);
}