public void AddSubKey(PgpKeyPair keyPair, PgpSignatureSubpacketVector hashedPackets, PgpSignatureSubpacketVector unhashedPackets) { try { PgpSignatureGenerator pgpSignatureGenerator = new PgpSignatureGenerator(masterKey.PublicKey.Algorithm, HashAlgorithmTag.Sha1); pgpSignatureGenerator.InitSign(24, masterKey.PrivateKey); pgpSignatureGenerator.SetHashedSubpackets(hashedPackets); pgpSignatureGenerator.SetUnhashedSubpackets(unhashedPackets); IList list = Platform.CreateArrayList(); list.Add(pgpSignatureGenerator.GenerateCertification(masterKey.PublicKey, keyPair.PublicKey)); keys.Add(new PgpSecretKey(keyPair.PrivateKey, new PgpPublicKey(keyPair.PublicKey, null, list), encAlgorithm, rawPassPhrase, clearPassPhrase: false, useSha1, rand, isMasterKey: false)); } catch (PgpException ex) { throw ex; } catch (Exception exception) { throw new PgpException("exception adding subkey: ", exception); } }
/// <summary> /// Sign public key with secret key. To access the private key from the /// secret container a password needs to be provided. /// </summary> /// <param name="secretKey"> /// The secret key containing the private key for signing the public /// key. /// </param> /// <param name="password"> /// The password of the secret key. /// </param> /// <param name="keyToBeSigned"> /// The public key to be signed. /// </param> /// <param name="certain"> /// Flag indicating whether or not the certification is positive or just /// casual. /// </param> /// <returns> /// Returns the <see cref="PgpPublicKey"/> adorned with a signature by the /// private key passed in. /// </returns> public static PgpPublicKey SignPublicKey( PgpSecretKey secretKey, string password, PgpPublicKey keyToBeSigned, bool certain) { var id = keyToBeSigned.GetUserIds().Cast <string>().FirstOrDefault(); // Extracting private key, and getting ready to create a signature. var privateKey = secretKey.ExtractPrivateKey(password.ToCharArray()); var signatureGenerator = new PgpSignatureGenerator(secretKey.PublicKey.Algorithm, HashAlgorithmTag.Sha256); signatureGenerator.InitSign( certain ? PgpSignature.PositiveCertification : PgpSignature.CasualCertification, privateKey); // Creating a stream to wrap the results of operation. var outputStream = new MemoryStream(); var packetOutputStream = new BcpgOutputStream(outputStream); signatureGenerator.GenerateOnePassVersion(false).Encode(packetOutputStream); // Creating a generator. var subpacketSignatureGenerator = new PgpSignatureSubpacketGenerator(); subpacketSignatureGenerator.SetSignerUserId(false, id); var packetVector = subpacketSignatureGenerator.Generate(); signatureGenerator.SetHashedSubpackets(packetVector); packetOutputStream.Flush(); // Returning the signed public key. return(PgpPublicKey.AddCertification( keyToBeSigned, id, signatureGenerator.GenerateCertification(id, keyToBeSigned))); }
public override void PerformTest() { // // RSA tests // PgpSecretKeyRing pgpPriv = new PgpSecretKeyRing(rsaKeyRing); IPgpSecretKey secretKey = pgpPriv.GetSecretKey(); IPgpPrivateKey pgpPrivKey = secretKey.ExtractPrivateKey(rsaPass); try { doTestSig(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey); Fail("RSA wrong key test failed."); } catch (PgpException) { // expected } try { doTestSigV3(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey); Fail("RSA V3 wrong key test failed."); } catch (PgpException) { // expected } // // certifications // PgpSignatureGenerator sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1); sGen.InitSign(PgpSignature.KeyRevocation, pgpPrivKey); PgpSignature sig = sGen.GenerateCertification(secretKey.PublicKey); sig.InitVerify(secretKey.PublicKey); if (!sig.VerifyCertification(secretKey.PublicKey)) { Fail("revocation verification failed."); } PgpSecretKeyRing pgpDSAPriv = new PgpSecretKeyRing(dsaKeyRing); IPgpSecretKey secretDSAKey = pgpDSAPriv.GetSecretKey(); IPgpPrivateKey pgpPrivDSAKey = secretDSAKey.ExtractPrivateKey(dsaPass); sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1); sGen.InitSign(PgpSignature.SubkeyBinding, pgpPrivDSAKey); PgpSignatureSubpacketGenerator unhashedGen = new PgpSignatureSubpacketGenerator(); PgpSignatureSubpacketGenerator hashedGen = new PgpSignatureSubpacketGenerator(); hashedGen.SetSignatureExpirationTime(false, TEST_EXPIRATION_TIME); hashedGen.SetSignerUserId(true, TEST_USER_ID); hashedGen.SetPreferredCompressionAlgorithms(false, PREFERRED_COMPRESSION_ALGORITHMS); hashedGen.SetPreferredHashAlgorithms(false, PREFERRED_HASH_ALGORITHMS); hashedGen.SetPreferredSymmetricAlgorithms(false, PREFERRED_SYMMETRIC_ALGORITHMS); sGen.SetHashedSubpackets(hashedGen.Generate()); sGen.SetUnhashedSubpackets(unhashedGen.Generate()); sig = sGen.GenerateCertification(secretDSAKey.PublicKey, secretKey.PublicKey); byte[] sigBytes = sig.GetEncoded(); PgpObjectFactory f = new PgpObjectFactory(sigBytes); sig = ((PgpSignatureList) f.NextPgpObject())[0]; sig.InitVerify(secretDSAKey.PublicKey); if (!sig.VerifyCertification(secretDSAKey.PublicKey, secretKey.PublicKey)) { Fail("subkey binding verification failed."); } var hashedPcks = sig.GetHashedSubPackets(); var unhashedPcks = sig.GetUnhashedSubPackets(); if (hashedPcks.Count != 6) { Fail("wrong number of hashed packets found."); } if (unhashedPcks.Count != 1) { Fail("wrong number of unhashed packets found."); } if (!hashedPcks.GetSignerUserId().Equals(TEST_USER_ID)) { Fail("test userid not matching"); } if (hashedPcks.GetSignatureExpirationTime() != TEST_EXPIRATION_TIME) { Fail("test signature expiration time not matching"); } if (unhashedPcks.GetIssuerKeyId() != secretDSAKey.KeyId) { Fail("wrong issuer key ID found in certification"); } int[] prefAlgs = hashedPcks.GetPreferredCompressionAlgorithms(); preferredAlgorithmCheck("compression", PREFERRED_COMPRESSION_ALGORITHMS, prefAlgs); prefAlgs = hashedPcks.GetPreferredHashAlgorithms(); preferredAlgorithmCheck("hash", PREFERRED_HASH_ALGORITHMS, prefAlgs); prefAlgs = hashedPcks.GetPreferredSymmetricAlgorithms(); preferredAlgorithmCheck("symmetric", PREFERRED_SYMMETRIC_ALGORITHMS, prefAlgs); SignatureSubpacketTag[] criticalHashed = hashedPcks.GetCriticalTags(); if (criticalHashed.Length != 1) { Fail("wrong number of critical packets found."); } if (criticalHashed[0] != SignatureSubpacketTag.SignerUserId) { Fail("wrong critical packet found in tag list."); } // // no packets passed // sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1); sGen.InitSign(PgpSignature.SubkeyBinding, pgpPrivDSAKey); sGen.SetHashedSubpackets(null); sGen.SetUnhashedSubpackets(null); sig = sGen.GenerateCertification(TEST_USER_ID, secretKey.PublicKey); sig.InitVerify(secretDSAKey.PublicKey); if (!sig.VerifyCertification(TEST_USER_ID, secretKey.PublicKey)) { Fail("subkey binding verification failed."); } hashedPcks = sig.GetHashedSubPackets(); if (hashedPcks.Count != 1) { Fail("found wrong number of hashed packets"); } unhashedPcks = sig.GetUnhashedSubPackets(); if (unhashedPcks.Count != 1) { Fail("found wrong number of unhashed packets"); } try { sig.VerifyCertification(secretKey.PublicKey); Fail("failed to detect non-key signature."); } catch (InvalidOperationException) { // expected } // // override hash packets // sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1); sGen.InitSign(PgpSignature.SubkeyBinding, pgpPrivDSAKey); hashedGen = new PgpSignatureSubpacketGenerator(); DateTime creationTime = new DateTime(1973, 7, 27); hashedGen.SetSignatureCreationTime(false, creationTime); sGen.SetHashedSubpackets(hashedGen.Generate()); sGen.SetUnhashedSubpackets(null); sig = sGen.GenerateCertification(TEST_USER_ID, secretKey.PublicKey); sig.InitVerify(secretDSAKey.PublicKey); if (!sig.VerifyCertification(TEST_USER_ID, secretKey.PublicKey)) { Fail("subkey binding verification failed."); } hashedPcks = sig.GetHashedSubPackets(); if (hashedPcks.Count != 1) { Fail("found wrong number of hashed packets in override test"); } if (!hashedPcks.HasSubpacket(SignatureSubpacketTag.CreationTime)) { Fail("hasSubpacket test for creation time failed"); } DateTime sigCreationTime = hashedPcks.GetSignatureCreationTime(); if (!sigCreationTime.Equals(creationTime)) { Fail("creation of overridden date failed."); } prefAlgs = hashedPcks.GetPreferredCompressionAlgorithms(); preferredAlgorithmCheck("compression", NO_PREFERENCES, prefAlgs); prefAlgs = hashedPcks.GetPreferredHashAlgorithms(); preferredAlgorithmCheck("hash", NO_PREFERENCES, prefAlgs); prefAlgs = hashedPcks.GetPreferredSymmetricAlgorithms(); preferredAlgorithmCheck("symmetric", NO_PREFERENCES, prefAlgs); if (hashedPcks.GetKeyExpirationTime() != 0) { Fail("unexpected key expiration time found"); } if (hashedPcks.GetSignatureExpirationTime() != 0) { Fail("unexpected signature expiration time found"); } if (hashedPcks.GetSignerUserId() != null) { Fail("unexpected signer user ID found"); } criticalHashed = hashedPcks.GetCriticalTags(); if (criticalHashed.Length != 0) { Fail("critical packets found when none expected"); } unhashedPcks = sig.GetUnhashedSubPackets(); if (unhashedPcks.Count != 1) { Fail("found wrong number of unhashed packets in override test"); } // // general signatures // doTestSig(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha256, secretKey.PublicKey, pgpPrivKey); doTestSig(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha384, secretKey.PublicKey, pgpPrivKey); doTestSig(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha512, secretKey.PublicKey, pgpPrivKey); doTestSigV3(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey); doTestTextSig(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA_WITH_CRLF, TEST_DATA_WITH_CRLF); doTestTextSig(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA, TEST_DATA_WITH_CRLF); doTestTextSigV3(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA_WITH_CRLF, TEST_DATA_WITH_CRLF); doTestTextSigV3(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA, TEST_DATA_WITH_CRLF); // // DSA Tests // pgpPriv = new PgpSecretKeyRing(dsaKeyRing); secretKey = pgpPriv.GetSecretKey(); pgpPrivKey = secretKey.ExtractPrivateKey(dsaPass); try { doTestSig(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey); Fail("DSA wrong key test failed."); } catch (PgpException) { // expected } try { doTestSigV3(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey); Fail("DSA V3 wrong key test failed."); } catch (PgpException) { // expected } doTestSig(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey); doTestSigV3(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey); doTestTextSig(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA_WITH_CRLF, TEST_DATA_WITH_CRLF); doTestTextSig(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA, TEST_DATA_WITH_CRLF); doTestTextSigV3(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA_WITH_CRLF, TEST_DATA_WITH_CRLF); doTestTextSigV3(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA, TEST_DATA_WITH_CRLF); // special cases // doTestMissingSubpackets(nullPacketsSubKeyBinding); doTestMissingSubpackets(generateV3BinarySig(pgpPrivKey, PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1)); // keyflags doTestKeyFlagsValues(); }
public override void PerformTest() { // // RSA tests // PgpSecretKeyRing pgpPriv = new PgpSecretKeyRing(rsaKeyRing); PgpSecretKey secretKey = pgpPriv.GetSecretKey(); PgpPrivateKey pgpPrivKey = secretKey.ExtractPrivateKey(rsaPass); try { doTestSig(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey); Fail("RSA wrong key test failed."); } catch (PgpException) { // expected } try { doTestSigV3(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey); Fail("RSA V3 wrong key test failed."); } catch (PgpException) { // expected } // // certifications // PgpSignatureGenerator sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1); sGen.InitSign(PgpSignature.KeyRevocation, pgpPrivKey); PgpSignature sig = sGen.GenerateCertification(secretKey.PublicKey); sig.InitVerify(secretKey.PublicKey); if (!sig.VerifyCertification(secretKey.PublicKey)) { Fail("revocation verification failed."); } PgpSecretKeyRing pgpDSAPriv = new PgpSecretKeyRing(dsaKeyRing); PgpSecretKey secretDSAKey = pgpDSAPriv.GetSecretKey(); PgpPrivateKey pgpPrivDSAKey = secretDSAKey.ExtractPrivateKey(dsaPass); sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1); sGen.InitSign(PgpSignature.SubkeyBinding, pgpPrivDSAKey); PgpSignatureSubpacketGenerator unhashedGen = new PgpSignatureSubpacketGenerator(); PgpSignatureSubpacketGenerator hashedGen = new PgpSignatureSubpacketGenerator(); hashedGen.SetSignatureExpirationTime(false, TEST_EXPIRATION_TIME); hashedGen.SetSignerUserId(true, TEST_USER_ID); hashedGen.SetPreferredCompressionAlgorithms(false, PREFERRED_COMPRESSION_ALGORITHMS); hashedGen.SetPreferredHashAlgorithms(false, PREFERRED_HASH_ALGORITHMS); hashedGen.SetPreferredSymmetricAlgorithms(false, PREFERRED_SYMMETRIC_ALGORITHMS); sGen.SetHashedSubpackets(hashedGen.Generate()); sGen.SetUnhashedSubpackets(unhashedGen.Generate()); sig = sGen.GenerateCertification(secretDSAKey.PublicKey, secretKey.PublicKey); byte[] sigBytes = sig.GetEncoded(); PgpObjectFactory f = new PgpObjectFactory(sigBytes); sig = ((PgpSignatureList)f.NextPgpObject())[0]; sig.InitVerify(secretDSAKey.PublicKey); if (!sig.VerifyCertification(secretDSAKey.PublicKey, secretKey.PublicKey)) { Fail("subkey binding verification failed."); } PgpSignatureSubpacketVector hashedPcks = sig.GetHashedSubPackets(); PgpSignatureSubpacketVector unhashedPcks = sig.GetUnhashedSubPackets(); if (hashedPcks.Count != 6) { Fail("wrong number of hashed packets found."); } if (unhashedPcks.Count != 1) { Fail("wrong number of unhashed packets found."); } if (!hashedPcks.GetSignerUserId().Equals(TEST_USER_ID)) { Fail("test userid not matching"); } if (hashedPcks.GetSignatureExpirationTime() != TEST_EXPIRATION_TIME) { Fail("test signature expiration time not matching"); } if (unhashedPcks.GetIssuerKeyId() != secretDSAKey.KeyId) { Fail("wrong issuer key ID found in certification"); } int[] prefAlgs = hashedPcks.GetPreferredCompressionAlgorithms(); preferredAlgorithmCheck("compression", PREFERRED_COMPRESSION_ALGORITHMS, prefAlgs); prefAlgs = hashedPcks.GetPreferredHashAlgorithms(); preferredAlgorithmCheck("hash", PREFERRED_HASH_ALGORITHMS, prefAlgs); prefAlgs = hashedPcks.GetPreferredSymmetricAlgorithms(); preferredAlgorithmCheck("symmetric", PREFERRED_SYMMETRIC_ALGORITHMS, prefAlgs); SignatureSubpacketTag[] criticalHashed = hashedPcks.GetCriticalTags(); if (criticalHashed.Length != 1) { Fail("wrong number of critical packets found."); } if (criticalHashed[0] != SignatureSubpacketTag.SignerUserId) { Fail("wrong critical packet found in tag list."); } // // no packets passed // sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1); sGen.InitSign(PgpSignature.SubkeyBinding, pgpPrivDSAKey); sGen.SetHashedSubpackets(null); sGen.SetUnhashedSubpackets(null); sig = sGen.GenerateCertification(TEST_USER_ID, secretKey.PublicKey); sig.InitVerify(secretDSAKey.PublicKey); if (!sig.VerifyCertification(TEST_USER_ID, secretKey.PublicKey)) { Fail("subkey binding verification failed."); } hashedPcks = sig.GetHashedSubPackets(); if (hashedPcks.Count != 1) { Fail("found wrong number of hashed packets"); } unhashedPcks = sig.GetUnhashedSubPackets(); if (unhashedPcks.Count != 1) { Fail("found wrong number of unhashed packets"); } try { sig.VerifyCertification(secretKey.PublicKey); Fail("failed to detect non-key signature."); } catch (InvalidOperationException) { // expected } // // override hash packets // sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1); sGen.InitSign(PgpSignature.SubkeyBinding, pgpPrivDSAKey); hashedGen = new PgpSignatureSubpacketGenerator(); DateTime creationTime = new DateTime(1973, 7, 27); hashedGen.SetSignatureCreationTime(false, creationTime); sGen.SetHashedSubpackets(hashedGen.Generate()); sGen.SetUnhashedSubpackets(null); sig = sGen.GenerateCertification(TEST_USER_ID, secretKey.PublicKey); sig.InitVerify(secretDSAKey.PublicKey); if (!sig.VerifyCertification(TEST_USER_ID, secretKey.PublicKey)) { Fail("subkey binding verification failed."); } hashedPcks = sig.GetHashedSubPackets(); if (hashedPcks.Count != 1) { Fail("found wrong number of hashed packets in override test"); } if (!hashedPcks.HasSubpacket(SignatureSubpacketTag.CreationTime)) { Fail("hasSubpacket test for creation time failed"); } DateTime sigCreationTime = hashedPcks.GetSignatureCreationTime(); if (!sigCreationTime.Equals(creationTime)) { Fail("creation of overridden date failed."); } prefAlgs = hashedPcks.GetPreferredCompressionAlgorithms(); preferredAlgorithmCheck("compression", NO_PREFERENCES, prefAlgs); prefAlgs = hashedPcks.GetPreferredHashAlgorithms(); preferredAlgorithmCheck("hash", NO_PREFERENCES, prefAlgs); prefAlgs = hashedPcks.GetPreferredSymmetricAlgorithms(); preferredAlgorithmCheck("symmetric", NO_PREFERENCES, prefAlgs); if (hashedPcks.GetKeyExpirationTime() != 0) { Fail("unexpected key expiration time found"); } if (hashedPcks.GetSignatureExpirationTime() != 0) { Fail("unexpected signature expiration time found"); } if (hashedPcks.GetSignerUserId() != null) { Fail("unexpected signer user ID found"); } criticalHashed = hashedPcks.GetCriticalTags(); if (criticalHashed.Length != 0) { Fail("critical packets found when none expected"); } unhashedPcks = sig.GetUnhashedSubPackets(); if (unhashedPcks.Count != 1) { Fail("found wrong number of unhashed packets in override test"); } // // general signatures // doTestSig(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha256, secretKey.PublicKey, pgpPrivKey); doTestSig(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha384, secretKey.PublicKey, pgpPrivKey); doTestSig(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha512, secretKey.PublicKey, pgpPrivKey); doTestSigV3(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey); doTestTextSig(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA_WITH_CRLF, TEST_DATA_WITH_CRLF); doTestTextSig(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA, TEST_DATA_WITH_CRLF); doTestTextSigV3(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA_WITH_CRLF, TEST_DATA_WITH_CRLF); doTestTextSigV3(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA, TEST_DATA_WITH_CRLF); // // DSA Tests // pgpPriv = new PgpSecretKeyRing(dsaKeyRing); secretKey = pgpPriv.GetSecretKey(); pgpPrivKey = secretKey.ExtractPrivateKey(dsaPass); try { doTestSig(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey); Fail("DSA wrong key test failed."); } catch (PgpException) { // expected } try { doTestSigV3(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey); Fail("DSA V3 wrong key test failed."); } catch (PgpException) { // expected } doTestSig(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey); doTestSigV3(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey); doTestTextSig(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA_WITH_CRLF, TEST_DATA_WITH_CRLF); doTestTextSig(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA, TEST_DATA_WITH_CRLF); doTestTextSigV3(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA_WITH_CRLF, TEST_DATA_WITH_CRLF); doTestTextSigV3(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA, TEST_DATA_WITH_CRLF); // special cases // doTestMissingSubpackets(nullPacketsSubKeyBinding); doTestMissingSubpackets(generateV3BinarySig(pgpPrivKey, PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1)); // keyflags doTestKeyFlagsValues(); }
public static void AddSignature(PgpPublicKey key, KeyStoreDB keyDb, string keyExportName, PgpSecretKey secKey, char[] passPhrase, SignatureOperation op, DateTime expiryDate, PgpSignature certLevel = null, string userId = "") { string fileData = string.Empty; bool useTemp = true; if (key == null) { throw new ArgumentNullException("key"); } if (keyDb == null) { throw new ArgumentNullException("keyDb"); } if (!Enum.IsDefined(typeof(SignatureOperation), op)) { throw new ArgumentOutOfRangeException(string.Format("op: {0}", op)); } AlgorithmAgreement algorithms = new AlgorithmAgreement(new List <PgpPublicKey>() { key }); PgpPrivateKey privateKey = secKey.ExtractPrivateKey(passPhrase); PgpSignatureGenerator sigGen = new PgpSignatureGenerator(key.Algorithm, algorithms.AgreedHashAlgorithm); switch (op) { case SignatureOperation.AddUserId: break; case SignatureOperation.RevokeKey: MemoryStream mStream = new MemoryStream(); using (ArmoredOutputStream outArmour = new ArmoredOutputStream(mStream)) { outArmour.SetHeader("Version", "Lynx Privacy"); sigGen.InitSign(PgpSignature.KeyRevocation, privateKey); PgpSignature sig = sigGen.GenerateCertification(secKey.PublicKey); PgpPublicKey.AddCertification(secKey.PublicKey, sig); sig.InitVerify(secKey.PublicKey); if (!sig.VerifyCertification(secKey.PublicKey)) { throw new PgpException("revocation verification failed."); } sig.Encode(outArmour); outArmour.Close(); } mStream.Position = 0; StreamReader srdr = new StreamReader(mStream); string armour = srdr.ReadToEnd(); string outstr = armour.Replace("BEGIN PGP SIGNATURE", "BEGIN PGP PUBLIC KEY BLOCK") .Replace("END PGP SIGNATURE", "END PGP PUBLIC KEY BLOCK"); mStream.Close(); if (string.IsNullOrEmpty(keyExportName)) { useTemp = true; string tempPath = Path.GetTempPath(); keyExportName = Path.Combine(tempPath, Guid.NewGuid().ToString() + ".tmppgp"); } File.WriteAllText(keyExportName, outstr); keyExportName = ""; //Debug.Assert(secKey.PublicKey.IsRevoked() == true); break; case SignatureOperation.SetKeyExpiry: break; case SignatureOperation.CertifyKey: break; default: break; } if (secKey.PublicKey != null) { if (string.IsNullOrEmpty(keyExportName)) { useTemp = true; string tempPath = Path.GetTempPath(); keyExportName = Path.Combine(tempPath, Guid.NewGuid().ToString() + ".tmppgp"); } ExportKey expKey = new ExportKey(keyDb); expKey.UpdateDbSecretKey(secKey, keyExportName); if (useTemp) { //File.Delete(keyExportName); } } }
public override void PerformTest() { // // Read the public key // PgpPublicKeyRing pgpPub = new PgpPublicKeyRing(testPubKey); AsymmetricKeyParameter pubKey = pgpPub.GetPublicKey().GetKey(); IEnumerator enumerator = pgpPub.GetPublicKey().GetUserIds().GetEnumerator(); enumerator.MoveNext(); string uid = (string) enumerator.Current; enumerator = pgpPub.GetPublicKey().GetSignaturesForId(uid).GetEnumerator(); enumerator.MoveNext(); PgpSignature sig = (PgpSignature) enumerator.Current; sig.InitVerify(pgpPub.GetPublicKey()); if (!sig.VerifyCertification(uid, pgpPub.GetPublicKey())) { Fail("failed to verify certification"); } // // write a public key // MemoryStream bOut = new UncloseableMemoryStream(); BcpgOutputStream pOut = new BcpgOutputStream(bOut); pgpPub.Encode(pOut); if (!Arrays.AreEqual(bOut.ToArray(), testPubKey)) { Fail("public key rewrite failed"); } // // Read the public key // PgpPublicKeyRing pgpPubV3 = new PgpPublicKeyRing(testPubKeyV3); AsymmetricKeyParameter pubKeyV3 = pgpPub.GetPublicKey().GetKey(); // // write a V3 public key // bOut = new UncloseableMemoryStream(); pOut = new BcpgOutputStream(bOut); pgpPubV3.Encode(pOut); // // Read a v3 private key // char[] passP = "FIXCITY_QA".ToCharArray(); { PgpSecretKeyRing pgpPriv2 = new PgpSecretKeyRing(testPrivKeyV3); PgpSecretKey pgpPrivSecretKey = pgpPriv2.GetSecretKey(); PgpPrivateKey pgpPrivKey2 = pgpPrivSecretKey.ExtractPrivateKey(passP); // // write a v3 private key // bOut = new UncloseableMemoryStream(); pOut = new BcpgOutputStream(bOut); pgpPriv2.Encode(pOut); byte[] result = bOut.ToArray(); if (!Arrays.AreEqual(result, testPrivKeyV3)) { Fail("private key V3 rewrite failed"); } } // // Read the private key // PgpSecretKeyRing pgpPriv = new PgpSecretKeyRing(testPrivKey); PgpPrivateKey pgpPrivKey = pgpPriv.GetSecretKey().ExtractPrivateKey(pass); // // write a private key // bOut = new UncloseableMemoryStream(); pOut = new BcpgOutputStream(bOut); pgpPriv.Encode(pOut); if (!Arrays.AreEqual(bOut.ToArray(), testPrivKey)) { Fail("private key rewrite failed"); } // // test encryption // IBufferedCipher c = CipherUtilities.GetCipher("RSA"); // c.Init(Cipher.ENCRYPT_MODE, pubKey); c.Init(true, pubKey); byte[] inBytes = Encoding.ASCII.GetBytes("hello world"); byte[] outBytes = c.DoFinal(inBytes); // c.Init(Cipher.DECRYPT_MODE, pgpPrivKey.GetKey()); c.Init(false, pgpPrivKey.Key); outBytes = c.DoFinal(outBytes); if (!Arrays.AreEqual(inBytes, outBytes)) { Fail("decryption failed."); } // // test signature message // PgpObjectFactory pgpFact = new PgpObjectFactory(sig1); 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(); ops.InitVerify(pgpPub.GetPublicKey(ops.KeyId)); int ch; while ((ch = dIn.ReadByte()) >= 0) { ops.Update((byte)ch); } PgpSignatureList p3 = (PgpSignatureList)pgpFact.NextPgpObject(); if (!ops.Verify(p3[0])) { Fail("Failed signature check"); } // // encrypted message - read subkey // pgpPriv = new PgpSecretKeyRing(subKey); // // encrypted message // byte[] text = Encoding.ASCII.GetBytes("hello world!\n"); PgpObjectFactory pgpF = new PgpObjectFactory(enc1); PgpEncryptedDataList encList = (PgpEncryptedDataList)pgpF.NextPgpObject(); PgpPublicKeyEncryptedData encP = (PgpPublicKeyEncryptedData)encList[0]; pgpPrivKey = pgpPriv.GetSecretKey(encP.KeyId).ExtractPrivateKey(pass); Stream clear = encP.GetDataStream(pgpPrivKey); pgpFact = new PgpObjectFactory(clear); c1 = (PgpCompressedData)pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(c1.GetDataStream()); PgpLiteralData ld = (PgpLiteralData)pgpFact.NextPgpObject(); if (!ld.FileName.Equals("test.txt")) { throw new Exception("wrong filename in packet"); } Stream inLd = ld.GetDataStream(); byte[] bytes = Streams.ReadAll(inLd); if (!Arrays.AreEqual(bytes, text)) { Fail("wrong plain text in decrypted packet"); } // // encrypt - short message // byte[] shortText = { (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o' }; MemoryStream cbOut = new UncloseableMemoryStream(); PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, new SecureRandom()); PgpPublicKey puK = pgpPriv.GetSecretKey(encP.KeyId).PublicKey; cPk.AddMethod(puK); Stream cOut = cPk.Open(new UncloseableStream(cbOut), shortText.Length); cOut.Write(shortText, 0, shortText.Length); cOut.Close(); pgpF = new PgpObjectFactory(cbOut.ToArray()); encList = (PgpEncryptedDataList)pgpF.NextPgpObject(); encP = (PgpPublicKeyEncryptedData)encList[0]; pgpPrivKey = pgpPriv.GetSecretKey(encP.KeyId).ExtractPrivateKey(pass); if (encP.GetSymmetricAlgorithm(pgpPrivKey) != SymmetricKeyAlgorithmTag.Cast5) { Fail("symmetric algorithm mismatch"); } clear = encP.GetDataStream(pgpPrivKey); outBytes = Streams.ReadAll(clear); if (!Arrays.AreEqual(outBytes, shortText)) { Fail("wrong plain text in generated short text packet"); } // // encrypt // cbOut = new UncloseableMemoryStream(); cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, new SecureRandom()); puK = pgpPriv.GetSecretKey(encP.KeyId).PublicKey; cPk.AddMethod(puK); cOut = cPk.Open(new UncloseableStream(cbOut), text.Length); cOut.Write(text, 0, text.Length); cOut.Close(); pgpF = new PgpObjectFactory(cbOut.ToArray()); encList = (PgpEncryptedDataList)pgpF.NextPgpObject(); encP = (PgpPublicKeyEncryptedData)encList[0]; pgpPrivKey = pgpPriv.GetSecretKey(encP.KeyId).ExtractPrivateKey(pass); clear = encP.GetDataStream(pgpPrivKey); outBytes = Streams.ReadAll(clear); if (!Arrays.AreEqual(outBytes, text)) { Fail("wrong plain text in generated packet"); } // // read public key with sub key. // pgpF = new PgpObjectFactory(subPubKey); object o; while ((o = pgpFact.NextPgpObject()) != null) { // TODO Should something be tested here? // Console.WriteLine(o); } // // key pair generation - CAST5 encryption // char[] passPhrase = "hello".ToCharArray(); IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator("RSA"); RsaKeyGenerationParameters genParam = new RsaKeyGenerationParameters( BigInteger.ValueOf(0x10001), new SecureRandom(), 1024, 25); kpg.Init(genParam); AsymmetricCipherKeyPair kp = kpg.GenerateKeyPair(); PgpSecretKey secretKey = new PgpSecretKey( PgpSignature.DefaultCertification, PublicKeyAlgorithmTag.RsaGeneral, kp.Public, kp.Private, DateTime.UtcNow, "fred", SymmetricKeyAlgorithmTag.Cast5, passPhrase, null, null, new SecureRandom() ); PgpPublicKey key = secretKey.PublicKey; enumerator = key.GetUserIds().GetEnumerator(); enumerator.MoveNext(); uid = (string) enumerator.Current; enumerator = key.GetSignaturesForId(uid).GetEnumerator(); enumerator.MoveNext(); sig = (PgpSignature) enumerator.Current; sig.InitVerify(key); if (!sig.VerifyCertification(uid, key)) { Fail("failed to verify certification"); } pgpPrivKey = secretKey.ExtractPrivateKey(passPhrase); key = PgpPublicKey.RemoveCertification(key, uid, sig); if (key == null) { Fail("failed certification removal"); } byte[] keyEnc = key.GetEncoded(); key = PgpPublicKey.AddCertification(key, uid, sig); keyEnc = key.GetEncoded(); PgpSignatureGenerator sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1); sGen.InitSign(PgpSignature.KeyRevocation, secretKey.ExtractPrivateKey(passPhrase)); sig = sGen.GenerateCertification(key); key = PgpPublicKey.AddCertification(key, sig); keyEnc = key.GetEncoded(); PgpPublicKeyRing tmpRing = new PgpPublicKeyRing(keyEnc); key = tmpRing.GetPublicKey(); IEnumerator sgEnum = key.GetSignaturesOfType(PgpSignature.KeyRevocation).GetEnumerator(); sgEnum.MoveNext(); sig = (PgpSignature) sgEnum.Current; sig.InitVerify(key); if (!sig.VerifyCertification(key)) { Fail("failed to verify revocation certification"); } // // use of PgpKeyPair // PgpKeyPair pgpKp = new PgpKeyPair(PublicKeyAlgorithmTag.RsaGeneral, kp.Public, kp.Private, DateTime.UtcNow); PgpPublicKey k1 = pgpKp.PublicKey; PgpPrivateKey k2 = pgpKp.PrivateKey; k1.GetEncoded(); MixedTest(k2, k1); // // key pair generation - AES_256 encryption. // kp = kpg.GenerateKeyPair(); secretKey = new PgpSecretKey(PgpSignature.DefaultCertification, PublicKeyAlgorithmTag.RsaGeneral, kp.Public, kp.Private, DateTime.UtcNow, "fred", SymmetricKeyAlgorithmTag.Aes256, passPhrase, null, null, new SecureRandom()); secretKey.ExtractPrivateKey(passPhrase); secretKey.Encode(new UncloseableMemoryStream()); // // secret key password changing. // const string newPass = "******"; secretKey = PgpSecretKey.CopyWithNewPassword(secretKey, passPhrase, newPass.ToCharArray(), secretKey.KeyEncryptionAlgorithm, new SecureRandom()); secretKey.ExtractPrivateKey(newPass.ToCharArray()); secretKey.Encode(new UncloseableMemoryStream()); key = secretKey.PublicKey; key.Encode(new UncloseableMemoryStream()); enumerator = key.GetUserIds().GetEnumerator(); enumerator.MoveNext(); uid = (string) enumerator.Current; enumerator = key.GetSignaturesForId(uid).GetEnumerator(); enumerator.MoveNext(); sig = (PgpSignature) enumerator.Current; sig.InitVerify(key); if (!sig.VerifyCertification(uid, key)) { Fail("failed to verify certification"); } pgpPrivKey = secretKey.ExtractPrivateKey(newPass.ToCharArray()); // // signature generation // const string data = "hello world!"; byte[] dataBytes = Encoding.ASCII.GetBytes(data); bOut = new UncloseableMemoryStream(); MemoryStream testIn = new MemoryStream(dataBytes, false); sGen = new PgpSignatureGenerator( PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1); sGen.InitSign(PgpSignature.BinaryDocument, pgpPrivKey); PgpCompressedDataGenerator cGen = new PgpCompressedDataGenerator( CompressionAlgorithmTag.Zip); BcpgOutputStream bcOut = new BcpgOutputStream(cGen.Open(new UncloseableStream(bOut))); sGen.GenerateOnePassVersion(false).Encode(bcOut); PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator(); DateTime testDateTime = new DateTime(1973, 7, 27); Stream lOut = lGen.Open(new UncloseableStream(bcOut), PgpLiteralData.Binary, "_CONSOLE", dataBytes.Length, testDateTime); // TODO Need a stream object to automatically call Update? // (via ISigner implementation of PgpSignatureGenerator) while ((ch = testIn.ReadByte()) >= 0) { lOut.WriteByte((byte)ch); sGen.Update((byte)ch); } lOut.Close(); sGen.Generate().Encode(bcOut); bcOut.Close(); // // verify generated signature // pgpFact = new PgpObjectFactory(bOut.ToArray()); c1 = (PgpCompressedData)pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(c1.GetDataStream()); p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject(); ops = p1[0]; p2 = (PgpLiteralData)pgpFact.NextPgpObject(); if (!p2.ModificationTime.Equals(testDateTime)) { Fail("Modification time not preserved"); } dIn = p2.GetInputStream(); ops.InitVerify(secretKey.PublicKey); // TODO Need a stream object to automatically call Update? // (via ISigner implementation of PgpSignatureGenerator) while ((ch = dIn.ReadByte()) >= 0) { ops.Update((byte)ch); } p3 = (PgpSignatureList)pgpFact.NextPgpObject(); if (!ops.Verify(p3[0])) { Fail("Failed generated signature check"); } // // signature generation - version 3 // bOut = new UncloseableMemoryStream(); testIn = new MemoryStream(dataBytes); PgpV3SignatureGenerator sGenV3 = new PgpV3SignatureGenerator( PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1); sGen.InitSign(PgpSignature.BinaryDocument, pgpPrivKey); cGen = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip); bcOut = new BcpgOutputStream(cGen.Open(new UncloseableStream(bOut))); sGen.GenerateOnePassVersion(false).Encode(bcOut); lGen = new PgpLiteralDataGenerator(); lOut = lGen.Open( new UncloseableStream(bcOut), PgpLiteralData.Binary, "_CONSOLE", dataBytes.Length, testDateTime); // TODO Need a stream object to automatically call Update? // (via ISigner implementation of PgpSignatureGenerator) while ((ch = testIn.ReadByte()) >= 0) { lOut.WriteByte((byte) ch); sGen.Update((byte)ch); } lOut.Close(); sGen.Generate().Encode(bcOut); bcOut.Close(); // // verify generated signature // pgpFact = new PgpObjectFactory(bOut.ToArray()); c1 = (PgpCompressedData)pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(c1.GetDataStream()); p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject(); ops = p1[0]; p2 = (PgpLiteralData)pgpFact.NextPgpObject(); if (!p2.ModificationTime.Equals(testDateTime)) { Fail("Modification time not preserved"); } dIn = p2.GetInputStream(); ops.InitVerify(secretKey.PublicKey); // TODO Need a stream object to automatically call Update? // (via ISigner implementation of PgpSignatureGenerator) while ((ch = dIn.ReadByte()) >= 0) { ops.Update((byte)ch); } p3 = (PgpSignatureList)pgpFact.NextPgpObject(); if (!ops.Verify(p3[0])) { Fail("Failed v3 generated signature check"); } // // extract PGP 8 private key // pgpPriv = new PgpSecretKeyRing(pgp8Key); secretKey = pgpPriv.GetSecretKey(); pgpPrivKey = secretKey.ExtractPrivateKey(pgp8Pass); // // other sig tests // PerformTestSig(HashAlgorithmTag.Sha256, secretKey.PublicKey, pgpPrivKey); PerformTestSig(HashAlgorithmTag.Sha384, secretKey.PublicKey, pgpPrivKey); PerformTestSig(HashAlgorithmTag.Sha512, secretKey.PublicKey, pgpPrivKey); FingerPrintTest(); ExistingEmbeddedJpegTest(); EmbeddedJpegTest(); }
private void EmbeddedJpegTest() { PgpPublicKeyRing pgpPub = new PgpPublicKeyRing(testPubKey); PgpSecretKeyRing pgpSec = new PgpSecretKeyRing(testPrivKey); PgpPublicKey pubKey = pgpPub.GetPublicKey(); PgpUserAttributeSubpacketVectorGenerator vGen = new PgpUserAttributeSubpacketVectorGenerator(); vGen.SetImageAttribute(ImageAttrib.Format.Jpeg, jpegImage); PgpUserAttributeSubpacketVector uVec = vGen.Generate(); PgpSignatureGenerator sGen = new PgpSignatureGenerator( PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1); sGen.InitSign(PgpSignature.PositiveCertification, pgpSec.GetSecretKey().ExtractPrivateKey(pass)); PgpSignature sig = sGen.GenerateCertification(uVec, pubKey); PgpPublicKey nKey = PgpPublicKey.AddCertification(pubKey, uVec, sig); int count = 0; foreach (PgpUserAttributeSubpacketVector attributes in nKey.GetUserAttributes()) { int sigCount = 0; foreach (PgpSignature s in nKey.GetSignaturesForUserAttribute(attributes)) { s.InitVerify(pubKey); if (!s.VerifyCertification(attributes, pubKey)) { Fail("added signature failed verification"); } sigCount++; } if (sigCount != 1) { Fail("Failed added user attributes signature check"); } count++; } if (count != 1) { Fail("didn't find added user attributes"); } nKey = PgpPublicKey.RemoveCertification(nKey, uVec); if (nKey.GetUserAttributes().GetEnumerator().MoveNext()) { Fail("found attributes where none expected"); } }
/// <summary> /// /// </summary> /// <param name="SecretKey"></param> /// <param name="Passhrase"></param> /// <param name="Reason"></param> /// <param name="RevokeDescription"></param> /// <returns></returns> public static PgpSignature GenerateSignature(PgpSecretKey SecretKey, char[] Passhrase, string Reason, string RevokeDescription) { RevocationReasonTag RevokeReason; if (string.Equals(Reason, "Compromised", StringComparison.CurrentCultureIgnoreCase)) { RevokeReason = RevocationReasonTag.KeyCompromised; } else if (string.Equals(Reason, "Retired", StringComparison.CurrentCultureIgnoreCase)) { RevokeReason = RevocationReasonTag.KeyRetired; } else if (string.Equals(Reason, "Superseded", StringComparison.CurrentCultureIgnoreCase)) { RevokeReason = RevocationReasonTag.KeySuperseded; } else if (string.Equals(Reason, "NoReason", StringComparison.CurrentCultureIgnoreCase)) { RevokeReason = RevocationReasonTag.NoReason; } else if (string.Equals(Reason, "Invalid", StringComparison.CurrentCultureIgnoreCase)) { RevokeReason = RevocationReasonTag.UserNoLongerValid; } else { RevokeReason = RevocationReasonTag.NoReason; } // Create the subpacket generators for the hashed and unhashed packets. var subHashGenerator = new PgpSignatureSubpacketGenerator(); var subUnHashGenerator = new PgpSignatureSubpacketGenerator(); // Extract the private key from the secret key. PgpPrivateKey privKey; try { privKey = SecretKey.ExtractPrivateKey(Passhrase); } catch { throw new PgpException("Wrong Passphrase, could not extract private key."); } // Create a signature generator and initialize it for key revocation. var generator = new PgpSignatureGenerator(SecretKey.PublicKey.Algorithm, HashAlgorithmTag.Sha256); generator.InitSign(PgpSignature.KeyRevocation, privKey, new SecureRandom()); // Create the hashed and unhashed subpackets and add them to the signature generator. subHashGenerator.SetSignatureCreationTime(false, DateTime.UtcNow); subHashGenerator.SetRevocationReason(false, RevokeReason, RevokeDescription); subUnHashGenerator.SetRevocationKey(false, SecretKey.PublicKey.Algorithm, SecretKey.PublicKey.GetFingerprint()); generator.SetHashedSubpackets(subHashGenerator.Generate()); generator.SetUnhashedSubpackets(subUnHashGenerator.Generate()); // Generate the certification var signature = generator.GenerateCertification(SecretKey.PublicKey); return(signature); }
/// <summary> /// /// </summary> /// <param name="SecretKey"></param> /// <param name="Passhrase"></param> /// <param name="Reason"></param> /// <param name="RevokeDescription"></param> /// <param name="OutFile"></param> public static void GenerateCertificate(PgpSecretKey SecretKey, char[] Passhrase, string Reason, string RevokeDescription, string OutFile) { RevocationReasonTag RevokeReason; if (string.Equals(Reason, "Compromised", StringComparison.CurrentCultureIgnoreCase)) { RevokeReason = RevocationReasonTag.KeyCompromised; } else if (string.Equals(Reason, "Retired", StringComparison.CurrentCultureIgnoreCase)) { RevokeReason = RevocationReasonTag.KeyRetired; } else if (string.Equals(Reason, "Superseded", StringComparison.CurrentCultureIgnoreCase)) { RevokeReason = RevocationReasonTag.KeySuperseded; } else if (string.Equals(Reason, "NoReason", StringComparison.CurrentCultureIgnoreCase)) { RevokeReason = RevocationReasonTag.NoReason; } else if (string.Equals(Reason, "Invalid", StringComparison.CurrentCultureIgnoreCase)) { RevokeReason = RevocationReasonTag.UserNoLongerValid; } else { RevokeReason = RevocationReasonTag.NoReason; } // Create the subpacket generators for the hashed and unhashed packets. var subHashGenerator = new PgpSignatureSubpacketGenerator(); var subUnHashGenerator = new PgpSignatureSubpacketGenerator(); // Extract the private key from the secret key. PgpPrivateKey privKey; try { privKey = SecretKey.ExtractPrivateKey(Passhrase); } catch { throw new PgpException("Wrong Passphrase, could not extract private key."); } // Create a signature generator and initialize it for key revocation. var generator = new PgpSignatureGenerator(SecretKey.PublicKey.Algorithm, HashAlgorithmTag.Sha256); generator.InitSign(PgpSignature.KeyRevocation, privKey, new SecureRandom()); // Create the hashed and unhashed subpackets and add them to the signature generator. subHashGenerator.SetSignatureCreationTime(false, DateTime.UtcNow); subHashGenerator.SetRevocationReason(false, RevokeReason, RevokeDescription); subUnHashGenerator.SetRevocationKey(false, SecretKey.PublicKey.Algorithm, SecretKey.PublicKey.GetFingerprint()); generator.SetHashedSubpackets(subHashGenerator.Generate()); generator.SetUnhashedSubpackets(subUnHashGenerator.Generate()); // Generate the certification var signature = generator.GenerateCertification(SecretKey.PublicKey); // Create the armour output stream and set the headers var mStream = new MemoryStream(); using (var outAStream = new ArmoredOutputStream(mStream)) { outAStream.SetHeader("Version", "Posh-OpenPGP"); outAStream.SetHeader("Comment", "A revocation certificate should follow"); signature.Encode(outAStream); outAStream.Close(); } // Turn the stream in to armour text and make sure we replace the propper headers mStream.Position = 0; var sr = new StreamReader(mStream); var armour = sr.ReadToEnd(); var outstr = armour.Replace("BEGIN PGP SIGNATURE", "BEGIN PGP PUBLIC KEY BLOCK").Replace("END PGP SIGNATURE", "END PGP PUBLIC KEY BLOCK"); // Save the string to the specified file. System.IO.File.WriteAllText(OutFile, outstr); }