public static byte[] ToAsc(byte[] pgp) { MemoryStream ms = new MemoryStream(); var ring = new PgpPublicKeyRing(GetStream(pgp)); var armored = new ArmoredOutputStream(ms); ring.Encode(armored); armored.Dispose(); return(ms.ToArray()); }
public void Encode(Stream outStr) { BcpgOutputStream outStr2 = BcpgOutputStream.Wrap(outStr); foreach (object item in order) { long num = (long)item; PgpPublicKeyRing pgpPublicKeyRing = (PgpPublicKeyRing)pubRings[num]; pgpPublicKeyRing.Encode(outStr2); } }
public void StoreKeyPair(PgpSecretKeyRing privateKey, PgpPublicKeyRing publicKey) { KeyPair keyPair = new KeyPair(); MemoryStream stream = new MemoryStream(); privateKey.Encode(stream); stream.Flush(); keyPair.PrivateKeyBlob = stream.ToArray(); stream = new MemoryStream(); publicKey.Encode(stream); stream.Flush(); keyPair.PublicKeyBlob = stream.ToArray(); keysdb.StoreKeyPair(keyPair); }
public void PerformTest() { // // Read the public key // PgpPublicKeyRing pgpPub = new PgpPublicKeyRing(testPubKey); var firstUserId = pgpPub.GetPublicKey().GetUserIds().FirstOrDefault(); Assert.NotNull(firstUserId); Assert.AreEqual(1, firstUserId.SelfCertifications.Count); Assert.IsTrue(firstUserId.SelfCertifications[0].Verify()); // // write a public key // MemoryStream bOut = new MemoryStream(); pgpPub.Encode(bOut); Assert.AreEqual(testPubKey, bOut.ToArray()); // // Read the public key // PgpPublicKeyRing pgpPubV3 = new PgpPublicKeyRing(testPubKeyV3); // // write a V3 public key // bOut = new MemoryStream(); pgpPubV3.Encode(bOut); // // Read a v3 private key // var passP = "FIXCITY_QA"; { PgpSecretKeyRing pgpPriv2 = new PgpSecretKeyRing(testPrivKeyV3); PgpSecretKey pgpPrivSecretKey = pgpPriv2.GetSecretKey(); PgpPrivateKey pgpPrivKey2 = pgpPrivSecretKey.ExtractPrivateKey(passP); // // write a v3 private key // bOut = new MemoryStream(); pgpPriv2.Encode(bOut); byte[] result = bOut.ToArray(); Assert.AreEqual(testPrivKeyV3, result); } // // Read the private key // PgpSecretKeyRing pgpPriv = new PgpSecretKeyRing(testPrivKey); PgpPrivateKey pgpPrivKey = pgpPriv.GetSecretKey().ExtractPrivateKey(pass); // // write a private key // bOut = new MemoryStream(); pgpPriv.Encode(bOut); Assert.AreEqual(testPrivKey, bOut.ToArray()); // // test encryption // /*var c = pubKey; * * // c.Init(Cipher.ENCRYPT_MODE, 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 // var compressedMessage = (PgpCompressedMessage)PgpMessage.ReadMessage(sig1); var signedMessage = (PgpSignedMessage)compressedMessage.ReadMessage(); var literalMessage = (PgpLiteralMessage)signedMessage.ReadMessage(); literalMessage.GetStream().CopyTo(Stream.Null); Assert.True(signedMessage.Verify(pgpPub.GetPublicKey(signedMessage.KeyId))); // // encrypted message - read subkey // pgpPriv = new PgpSecretKeyRing(subKey); // // encrypted message // byte[] text = Encoding.ASCII.GetBytes("hello world!\n"); var encryptedMessage = (PgpEncryptedMessage)PgpMessage.ReadMessage(enc1); var encKeyId = encryptedMessage.KeyIds.First(); pgpPrivKey = pgpPriv.GetSecretKey(encKeyId).ExtractPrivateKey(pass); compressedMessage = (PgpCompressedMessage)encryptedMessage.DecryptMessage(pgpPrivKey); literalMessage = (PgpLiteralMessage)compressedMessage.ReadMessage(); Assert.AreEqual("test.txt", literalMessage.FileName); byte[] bytes = Streams.ReadAll(literalMessage.GetStream()); Assert.AreEqual(text, bytes); // // encrypt - short message // byte[] shortText = { (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o' }; MemoryStream cbOut = new MemoryStream(); var messageGenerator = new PgpMessageGenerator(cbOut); using (var encryptedGenerator = messageGenerator.CreateEncrypted(PgpSymmetricKeyAlgorithm.Cast5)) { encryptedGenerator.AddMethod(pgpPriv.GetSecretKey(encKeyId)); using (var literalStream = encryptedGenerator.CreateLiteral(PgpDataFormat.Binary, "", DateTime.UtcNow)) { literalStream.Write(shortText); } } cbOut.Position = 0; encryptedMessage = (PgpEncryptedMessage)PgpMessage.ReadMessage(cbOut); pgpPrivKey = pgpPriv.GetSecretKey(encryptedMessage.KeyIds.First()).ExtractPrivateKey(pass); //Assert.AreEqual(SymmetricKeyAlgorithmTag.Cast5, ((PgpPublicKeyEncryptedData)encryptedMessage.Methods[0]).GetSymmetricAlgorithm(pgpPrivKey)); literalMessage = (PgpLiteralMessage)encryptedMessage.DecryptMessage(pgpPrivKey); Assert.AreEqual("", literalMessage.FileName); bytes = Streams.ReadAll(literalMessage.GetStream()); Assert.AreEqual(shortText, bytes); // // encrypt // cbOut = new MemoryStream(); messageGenerator = new PgpMessageGenerator(cbOut); using (var encryptedGenerator = messageGenerator.CreateEncrypted(PgpSymmetricKeyAlgorithm.Cast5)) { encryptedGenerator.AddMethod(pgpPriv.GetSecretKey(encKeyId)); using (var literalStream = encryptedGenerator.CreateLiteral(PgpDataFormat.Binary, "", DateTime.UtcNow)) { literalStream.Write(text); } } cbOut.Position = 0; encryptedMessage = (PgpEncryptedMessage)PgpMessage.ReadMessage(cbOut); pgpPrivKey = pgpPriv.GetSecretKey(encryptedMessage.KeyIds.First()).ExtractPrivateKey(pass); literalMessage = (PgpLiteralMessage)encryptedMessage.DecryptMessage(pgpPrivKey); bytes = Streams.ReadAll(literalMessage.GetStream()); Assert.AreEqual(text, bytes); // // 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 // var passPhrase = "hello"; var rsa = RSA.Create(1024); var keyRingGenerator = new PgpKeyRingGenerator(rsa, "fred", passPhrase); var secretKey = keyRingGenerator.GenerateSecretKeyRing().GetSecretKey(); PgpPublicKey key = new PgpPublicKey(secretKey); firstUserId = key.GetUserIds().FirstOrDefault(); Assert.NotNull(firstUserId); Assert.AreEqual(1, firstUserId.SelfCertifications.Count); Assert.IsTrue(firstUserId.SelfCertifications[0].Verify()); pgpPrivKey = secretKey.ExtractPrivateKey(passPhrase); key = PgpPublicKey.RemoveCertification(key, firstUserId, firstUserId.SelfCertifications[0]); Assert.NotNull(key); byte[] keyEnc = key.GetEncoded(); key = PgpPublicKey.AddCertification(key, firstUserId.UserId, firstUserId.SelfCertifications[0]); keyEnc = key.GetEncoded(); var revocation = PgpCertification.GenerateKeyRevocation( secretKey, secretKey.ExtractPrivateKey(passPhrase), key); key = PgpPublicKey.AddCertification(key, revocation); keyEnc = key.GetEncoded(); PgpPublicKeyRing tmpRing = new PgpPublicKeyRing(keyEnc); key = tmpRing.GetPublicKey(); revocation = key.KeyCertifications.Where(c => c.SignatureType == PgpSignatureType.KeyRevocation).FirstOrDefault(); Assert.NotNull(revocation); Assert.IsTrue(revocation.Verify(key)); // // use of PgpKeyPair // PgpKeyPair pgpKp = new PgpKeyPair(rsa, DateTime.UtcNow); PgpPublicKey k1 = pgpKp.PublicKey; PgpPrivateKey k2 = pgpKp.PrivateKey; k1.GetEncoded(); MixedTest(k2, k1); // // key pair generation - AES_256 encryption. -- XXX // //kp = kpg.GenerateKeyPair(); rsa = RSA.Create(1024); keyRingGenerator = new PgpKeyRingGenerator(rsa, "fred", passPhrase /*, encAlgorithm: PgpSymmetricKeyAlgorithm.Aes256*/); secretKey = keyRingGenerator.GenerateSecretKeyRing().GetSecretKey(); secretKey.ExtractPrivateKey(passPhrase); secretKey.Encode(new MemoryStream()); // // secret key password changing. // const string newPass = "******"; secretKey = PgpSecretKey.CopyWithNewPassword(secretKey, passPhrase, newPass); secretKey.ExtractPrivateKey(newPass); secretKey.Encode(new MemoryStream()); key = new PgpPublicKey(secretKey); key.Encode(new MemoryStream()); firstUserId = key.GetUserIds().FirstOrDefault(); Assert.NotNull(firstUserId); Assert.AreEqual(1, firstUserId.SelfCertifications.Count); Assert.IsTrue(firstUserId.SelfCertifications[0].Verify()); pgpPrivKey = secretKey.ExtractPrivateKey(newPass); // // signature generation // const string data = "hello world!"; byte[] dataBytes = Encoding.ASCII.GetBytes(data); DateTime testDateTime = new DateTime(1973, 7, 27); bOut = new MemoryStream(); messageGenerator = new PgpMessageGenerator(bOut); using (var compressedGenerator = messageGenerator.CreateCompressed(PgpCompressionAlgorithm.Zip)) using (var signingGenerator = compressedGenerator.CreateSigned(PgpSignatureType.BinaryDocument, pgpPrivKey, PgpHashAlgorithm.Sha1)) using (var literalStream = signingGenerator.CreateLiteral(PgpDataFormat.Binary, "_CONSOLE", testDateTime)) { literalStream.Write(dataBytes); } // // verify generated signature // bOut.Position = 0; compressedMessage = (PgpCompressedMessage)PgpMessage.ReadMessage(bOut); signedMessage = (PgpSignedMessage)compressedMessage.ReadMessage(); literalMessage = (PgpLiteralMessage)signedMessage.ReadMessage(); Assert.AreEqual(testDateTime, literalMessage.ModificationTime); literalMessage.GetStream().CopyTo(Stream.Null); Assert.IsTrue(signedMessage.Verify(secretKey)); // // signature generation - version 3 // bOut = new MemoryStream(); messageGenerator = new PgpMessageGenerator(bOut); using (var compressedGenerator = messageGenerator.CreateCompressed(PgpCompressionAlgorithm.Zip)) using (var signingGenerator = compressedGenerator.CreateSigned(PgpSignatureType.BinaryDocument, pgpPrivKey, PgpHashAlgorithm.Sha1, version: 3)) using (var literalStream = signingGenerator.CreateLiteral(PgpDataFormat.Binary, "_CONSOLE", testDateTime)) { literalStream.Write(dataBytes); } // // verify generated signature // bOut.Position = 0; compressedMessage = (PgpCompressedMessage)PgpMessage.ReadMessage(bOut); signedMessage = (PgpSignedMessage)compressedMessage.ReadMessage(); literalMessage = (PgpLiteralMessage)signedMessage.ReadMessage(); Assert.AreEqual(testDateTime, literalMessage.ModificationTime); literalMessage.GetStream().CopyTo(Stream.Null); Assert.IsTrue(signedMessage.Verify(secretKey)); // // extract PGP 8 private key // pgpPriv = new PgpSecretKeyRing(pgp8Key); secretKey = pgpPriv.GetSecretKey(); pgpPrivKey = secretKey.ExtractPrivateKey(pgp8Pass); // // other sig tests // PerformTestSig(PgpHashAlgorithm.Sha256, secretKey, pgpPrivKey); PerformTestSig(PgpHashAlgorithm.Sha384, secretKey, pgpPrivKey); PerformTestSig(PgpHashAlgorithm.Sha512, secretKey, pgpPrivKey); }
public void TestMethod1() { string secretKeyFile = @"-----BEGIN PGP PRIVATE KEY BLOCK----- Version: BCPG C# v1.7.4137.9688 lQc0BFTbeXUBEACgRx6VZYo0M8Vhv7D+ukhEPAIQHmbv41oae3vCINyEk+qdlkRQ qa+prxLyM3wvHi2WyUQUG67TgEhOKGiu5iRT3SDf7/o2+GyzkcJxVf4SsauvPNM9 chRtayHhtgNbkz+qS3G+zGgO52ck/W9J4EvxzeMaV+hN9TJm4nurZ52ZxqjxXDX2 9/loc639n/OCQTx3BKNPwt8TE3vaHUi7QScfL3Yj/zL3FDR8ct2Ymh4xWM2GjTb6 3mPWAt0pOfFOS0wxWpWYg9gl3p6iw8Sl7O5cqlxNlpA3b1b4mdF1v96kNfxkT4MI lNhfeNQ6e9cUZbMSJxt/gzY29xERa7kYpVC5QOgI57VZg/hsO8Uoh55H7LgKQ8Zw y4IQ/BZxBvMgBMVjYOHyhfC1rx81btPZbMHN6rwQFlXgXc+pbKTSzxmsCh00lc9z Ib653ByqHLeF4H++T6aU7L15C+8xOuFctF1wYLGjnr6ZX5tZINuyOqq2ifQ0wkkk xu7Ev/AIhE9oOYmn8HfwbUZOb28FbSqYssxzI76QTaPzOULJ+q/M94Z6WCTyXxHV uTFbhhlOn6FMK4AbUAseLO34w8rxYuwL50XdUlapW6yCxbtJILa118KxuC3CLxc5 Scfi//yDmlfqc+fYDLQu2173G5+PsSaTAs9xr6tedhRzpuWg63VyOnA3BQARAQAB /wkDAplemXfJ8EImYBVeK6Wpxj7yffXhSTElCFoRzQYDW1fv6RDytlxLPLHtpAG3 TQJTttt49uctJg6dpOhx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p0NO4/NvJG+ySw5kqVaR0W8yJ7Jat mqcuSIOyrw9X69uzoIzMNv2vmzN3F3czg5VGRcQVcDU0GVhq8VFUBBhQLUGiNFJM QO8KIwcFabhhu5ymAGTnyBBfetDr+0pqOLol0WKDFz4IF9DeLnESRqcl00Evx7/o viUOB7IZCHwFa3yRoyM8ZC2/p3phK8dreV2xPaPyyNbkl0768Spoa7s+59D9MoXC TP0+SvCeBf8jJpJ6/O/xUAvyPRvyk75+H6kOu0+4G7erK0AABb1WQvmYah1wPzD3 1ptfooPAKf193dtiOC2AoJdGu/oFmffgh0WhcbPCKlHv0zecx0DTGDkAQWAe9L+i BQ7R6w== =Z4JC -----END PGP PRIVATE KEY BLOCK-----"; File.WriteAllText(Path.Combine(@"C:\Users\John\BcPGP", "testuser1@example_com_secret.asc"), secretKeyFile); MemoryStream msSec = new MemoryStream(Encoding.UTF8.GetBytes(secretKeyFile)); PgpSecretKeyRing secRing = new PgpSecretKeyRing(PgpUtilities.GetDecoderStream(msSec)); char[] passPhrase = new char[] { 't', 'e', 's', 't', 'u', 's', 'e', 'r' }; PgpPublicKeyRing pubRing = new PgpPublicKeyRing(secRing.GetPublicKey().GetEncoded()); PgpPublicKeyRing newRing = new PgpPublicKeyRing( new MemoryStream(RevokePublicKey(secRing.GetSecretKey(), passPhrase, pubRing.GetPublicKey(), true))); msSec.Close(); Assert.IsTrue(newRing.GetPublicKey().IsRevoked()); Stream fos = File.Create(@"C:\Users\John\BcPGP\RevokedKey.asc"); ArmoredOutputStream aOut = new ArmoredOutputStream(fos); newRing.Encode(aOut); aOut.Close(); fos.Close(); PgpSecretKey newSecret = PgpSecretKey.ReplacePublicKey(secRing.GetSecretKey(), newRing.GetPublicKey()); Stream foSec = File.Create(@"C:\Users\John\BcPGP\SecretRevokedKey.asc"); ArmoredOutputStream sOut = new ArmoredOutputStream(foSec); newSecret.Encode(sOut); sOut.Close(); foSec.Close(); Assert.IsTrue(newSecret.PublicKey.IsRevoked()); }
public static void Main( string[] args) { if (args.Length == 1) { Stream fis = File.OpenRead(args[0]); PgpPublicKeyRing ring = new PgpPublicKeyRing( PgpUtilities.GetDecoderStream(fis)); PgpPublicKey key = ring.GetPublicKey(); // iterate through all direct key signautures and look for NotationData subpackets foreach (PgpSignature sig in key.GetSignaturesOfType(PgpSignature.DirectKey)) { Console.WriteLine("Signature date is: " + sig.GetHashedSubPackets().GetSignatureCreationTime()); NotationData[] data = sig.GetHashedSubPackets().GetNotationDataOccurrences(); for (int i = 0; i < data.Length; i++) { Console.WriteLine("Found Notation named '" + data[i].GetNotationName() + "' with content '" + data[i].GetNotationValue() + "'."); } } fis.Close(); } else if (args.Length == 5) { Stream secFis = File.OpenRead(args[0]); Stream pubFis = File.OpenRead(args[2]); // gather command line arguments PgpSecretKeyRing secRing = new PgpSecretKeyRing( PgpUtilities.GetDecoderStream(secFis)); String secretKeyPass = args[1]; PgpPublicKeyRing ring = new PgpPublicKeyRing( PgpUtilities.GetDecoderStream(pubFis)); String notationName = args[3]; String notationValue = args[4]; // create the signed keyRing PgpPublicKeyRing sRing = null; sRing = new PgpPublicKeyRing( new MemoryStream( SignPublicKey(secRing.GetSecretKey(), secretKeyPass, ring.GetPublicKey(), notationName, notationValue, true), false)); ring = sRing; secFis.Close(); pubFis.Close(); Stream fos = File.Create("SignedKey.asc"); // write the created keyRing to file ArmoredOutputStream aOut = new ArmoredOutputStream(fos); sRing.Encode(aOut); aOut.Close(); // Note: ArmoredOutputStream.Close() leaves underlying stream open fos.Close(); } else { Console.Error.WriteLine("usage: DirectKeySignature secretKeyFile secretKeyPass publicKeyFile(key to be signed) NotationName NotationValue"); Console.Error.WriteLine("or: DirectKeySignature signedPublicKeyFile"); } }
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(); }
public static void Main(string[] args) { if (args.Length == 1) { Stream fis = File.OpenRead(args[0]); var ring = new PgpPublicKeyRing( PgpUtilities.GetDecoderStream(fis)); var key = ring.GetPublicKey(); // iterate through all direct key signautures and look for NotationData subpackets foreach (PgpSignature sig in key.GetSignaturesOfType(PgpSignature.DirectKey)) { Console.WriteLine("Signature date is: " + sig.GetHashedSubPackets().GetSignatureCreationTime()); var data = sig.GetHashedSubPackets().GetNotationDataOccurences(); for (int i = 0; i < data.Length; i++) { Console.WriteLine("Found Notaion named '" + data[i].GetNotationName() +"' with content '" + data[i].GetNotationValue() + "'."); } } fis.Close(); } else if (args.Length == 5) { Stream secFis = File.OpenRead(args[0]); Stream pubFis = File.OpenRead(args[2]); // gather command line arguments PgpSecretKeyRing secRing = new PgpSecretKeyRing( PgpUtilities.GetDecoderStream(secFis)); String secretKeyPass = args[1]; PgpPublicKeyRing ring = new PgpPublicKeyRing( PgpUtilities.GetDecoderStream(pubFis)); String notationName = args[3]; String notationValue = args[4]; // create the signed keyRing PgpPublicKeyRing sRing = null; sRing = new PgpPublicKeyRing( new MemoryStream( SignPublicKey(secRing.GetSecretKey(), secretKeyPass, ring.GetPublicKey(), notationName, notationValue, true), false)); ring = sRing; secFis.Close(); pubFis.Close(); Stream fos = File.Create("SignedKey.asc"); // write the created keyRing to file ArmoredOutputStream aOut = new ArmoredOutputStream(fos); sRing.Encode(aOut); aOut.Close(); // Note: ArmoredOutputStream.Close() leaves underlying stream open fos.Close(); } else { Console.Error.WriteLine("usage: DirectKeySignature secretKeyFile secretKeyPass publicKeyFile(key to be signed) NotationName NotationValue"); Console.Error.WriteLine("or: DirectKeySignature signedPublicKeyFile"); } }