public void SignatureGenerateAndVerify() { var pgpPub = new PgpPublicKeyRing(testPubKeyRing); var pubKey = pgpPub.GetPublicKey(); var sKey = new PgpSecretKeyRing(testPrivKeyRing); var secretKey = sKey.GetSecretKey(); var privKey = secretKey.ExtractPrivateKey(pass); // Generate signature MemoryStream bOut = new MemoryStream(); DateTime testDateTime = new DateTime(1973, 7, 27); var messageGenerator = new PgpMessageGenerator(bOut); using (var compressedGenerator = messageGenerator.CreateCompressed(PgpCompressionAlgorithm.Zip)) using (var signingGenerator = compressedGenerator.CreateSigned(PgpSignatureType.BinaryDocument, privKey, PgpHashAlgorithm.Sha1)) using (var literalStream = signingGenerator.CreateLiteral(PgpDataFormat.Binary, "_CONSOLE", testDateTime)) literalStream.Write(text); // Verify generated signature bOut.Position = 0; var compressedMessage = (PgpCompressedMessage)PgpMessage.ReadMessage(bOut); var signedMessage = (PgpSignedMessage)compressedMessage.ReadMessage(); var literalMessage = (PgpLiteralMessage)signedMessage.ReadMessage(); Assert.AreEqual(testDateTime, literalMessage.ModificationTime); literalMessage.GetStream().CopyTo(Stream.Null); Assert.IsTrue(signedMessage.Verify(pubKey)); }
//[TestCase("DSA-2048-224.sec", "DSA-2048-224.pub", PgpHashAlgorithm.Sha256)] //[TestCase("DSA-2048-224.sec", "DSA-2048-224.pub", PgpHashAlgorithm.Sha512)] public void GenerateTest(string privateKeyFile, string publicKeyFile, PgpHashAlgorithm digest) { PgpSecretKeyRing secRing = loadSecretKey(privateKeyFile); PgpPublicKeyRing pubRing = loadPublicKey(publicKeyFile); string data = "hello world!"; byte[] dataBytes = Encoding.ASCII.GetBytes(data); MemoryStream bOut = new MemoryStream(); DateTime testDate = new DateTime((DateTime.UtcNow.Ticks / TimeSpan.TicksPerSecond) * TimeSpan.TicksPerSecond); var messageGenerator = new PgpMessageGenerator(bOut); using (var signingGenerator = messageGenerator.CreateSigned(PgpSignatureType.BinaryDocument, secRing.GetSecretKey().ExtractPrivateKey("test"), digest)) using (var literalStream = signingGenerator.CreateLiteral(PgpDataFormat.Binary, "_CONSOLE", testDate)) { literalStream.Write(dataBytes); } bOut.Position = 0; var signedMessage = (PgpSignedMessage)PgpMessage.ReadMessage(bOut); Assert.AreEqual(digest, signedMessage.HashAlgorithm); Assert.AreEqual(PgpPublicKeyAlgorithm.Dsa, signedMessage.KeyAlgorithm); var literalMessage = (PgpLiteralMessage)signedMessage.ReadMessage(); Assert.AreEqual(testDate, literalMessage.ModificationTime); literalMessage.GetStream().CopyTo(Stream.Null); Assert.IsTrue(signedMessage.Verify(pubRing.GetPublicKey())); }
public void EncryptDecryptX25519KeysTest() { PgpPublicKeyRing publicKeyRing = new PgpPublicKeyRing(testX25519PubKey); PgpSecretKeyRing secretKeyRing = new PgpSecretKeyRing(testX25519PrivKey); PgpSecretKey secretKey = secretKeyRing.GetSecretKey(0x6c37367cd2f455c5); byte[] text = Encoding.ASCII.GetBytes("hello world!"); // Encrypt text MemoryStream cbOut = new MemoryStream(); var messageGenerator = new PgpMessageGenerator(cbOut); using (var encryptedGenerator = messageGenerator.CreateEncrypted(PgpSymmetricKeyAlgorithm.Cast5)) { encryptedGenerator.AddMethod(publicKeyRing.GetPublicKey(0x6c37367cd2f455c5)); using (var literalStream = encryptedGenerator.CreateLiteral(PgpDataFormat.Utf8, "_CONSOLE", DateTime.UtcNow)) literalStream.Write(text); } // Read it back cbOut.Position = 0; var encryptedMessage = (PgpEncryptedMessage)PgpMessage.ReadMessage(cbOut); var literalMessage = (PgpLiteralMessage)encryptedMessage.DecryptMessage(secretKey.ExtractPrivateKey("test")); var bytes = Streams.ReadAll(literalMessage.GetStream()); Assert.AreEqual(text, bytes); }
public void ReadUserAttributes() { // // Read the public key with user attributes // var pgpPub = new PgpPublicKeyRing(testPubWithUserAttr); var pubKey = pgpPub.GetPublicKey(); int count = 0; foreach (PgpUser attributes in pubKey.GetUserAttributes()) { Assert.AreEqual(1, attributes.SelfCertifications.Count); Assert.AreEqual(0, attributes.OtherCertifications.Count); Assert.AreEqual(0, attributes.RevocationSignatures.Count); count++; } Assert.AreEqual(1, count); byte[] pgpPubBytes = pgpPub.GetEncoded(); pgpPub = new PgpPublicKeyRing(pgpPubBytes); pubKey = pgpPub.GetPublicKey(); count = 0; foreach (object ua in pubKey.GetUserAttributes()) { Assert.NotNull(ua); count++; } Assert.AreEqual(1, count); }
public void AddKey(string publicKey, bool nonErasable = false) { using (var s = Tools.GenerateStreamFromString(publicKey)) { var pgpPub = new PgpPublicKeyRing(PgpUtilities.GetDecoderStream(s)); var pubKey = pgpPub.GetPublicKey(); AddKey(pubKey, nonErasable); } }
//[TestCase("DSA-7680-384.pub", "dsa-7680-384-sign.gpg")] //[TestCase("DSA-15360-512.pub", "dsa-15360-512-sign.gpg")] public void SignatureVerifyTest(string publicKeyFile, string sigFile) { PgpPublicKeyRing publicKey = loadPublicKey(publicKeyFile); var compressedMessage = (PgpCompressedMessage)PgpMessage.ReadMessage(loadSig(sigFile)); var signedMessage = (PgpSignedMessage)compressedMessage.ReadMessage(); var literalMessage = (PgpLiteralMessage)signedMessage.ReadMessage(); literalMessage.GetStream().CopyTo(Stream.Null); Assert.IsTrue(signedMessage.Verify(publicKey.GetPublicKey())); }
public static PgpSecretKeyRing ReplacePublicKeys(PgpSecretKeyRing secretRing, PgpPublicKeyRing publicRing) { IList list = Platform.CreateArrayList(secretRing.keys.Count); foreach (PgpSecretKey key in secretRing.keys) { PgpPublicKey publicKey = publicRing.GetPublicKey(key.KeyId); list.Add(PgpSecretKey.ReplacePublicKey(key, publicKey)); } return(new PgpSecretKeyRing(list)); }
public void Setup() { // Read the public key var pgpPub = new PgpPublicKeyRing(testPubKey); pubKey = pgpPub.GetPublicKey(); // Read the private key var sKey = new PgpSecretKeyRing(testPrivKey); secretKey = sKey.GetSecretKey(); pgpPrivKey = secretKey.ExtractPrivateKey(pass); }
/// <summary> /// ## LoadPublicKey /// /// Loads a PGP public key from disk. /// </summary> /// <param name="path"></param> /// <returns></returns> public PgpPublicKey LoadPublicKey(string path) { using (Stream fs = File.OpenRead(path)) { using (Stream decoderStream = PgpUtilities.GetDecoderStream(fs)) { PgpPublicKeyRing keyRing = new PgpPublicKeyRing(decoderStream); decoderStream.Close(); fs.Close(); return(keyRing.GetPublicKey()); } } }
public void DoTestRemoveSignature() { byte[] testPubKeyRing = Convert.FromBase64String( "mQGiBEAR8jYRBADNifuSopd20JOQ5x30ljIaY0M6927+vo09NeNxS3KqItba" + "nz9o5e2aqdT0W1xgdHYZmdElOHTTsugZxdXTEhghyxoo3KhVcNnTABQyrrvX" + "qouvmP2fEDEw0Vpyk+90BpyY9YlgeX/dEA8OfooRLCJde/iDTl7r9FT+mts8" + "g3azjwCgx+pOLD9LPBF5E4FhUOdXISJ0f4EEAKXSOi9nZzajpdhe8W2ZL9gc" + "BpzZi6AcrRZBHOEMqd69gtUxA4eD8xycUQ42yH89imEcwLz8XdJ98uHUxGJi" + "qp6hq4oakmw8GQfiL7yQIFgaM0dOAI9Afe3m84cEYZsoAFYpB4/s9pVMpPRH" + "NsVspU0qd3NHnSZ0QXs8L8DXGO1uBACjDUj+8GsfDCIP2QF3JC+nPUNa0Y5t" + "wKPKl+T8hX/0FBD7fnNeC6c9j5Ir/Fp/QtdaDAOoBKiyNLh1JaB1NY6US5zc" + "qFks2seZPjXEiE6OIDXYra494mjNKGUobA4hqT2peKWXt/uBcuL1mjKOy8Qf" + "JxgEd0MOcGJO+1PFFZWGzLQ3RXJpYyBILiBFY2hpZG5hICh0ZXN0IGtleSBv" + "bmx5KSA8ZXJpY0Bib3VuY3ljYXN0bGUub3JnPohZBBMRAgAZBQJAEfI2BAsH" + "AwIDFQIDAxYCAQIeAQIXgAAKCRAOtk6iUOgnkDdnAKC/CfLWikSBdbngY6OK" + "5UN3+o7q1ACcDRqjT3yjBU3WmRUNlxBg3tSuljmwAgAAuQENBEAR8jgQBAC2" + "kr57iuOaV7Ga1xcU14MNbKcA0PVembRCjcVjei/3yVfT/fuCVtGHOmYLEBqH" + "bn5aaJ0P/6vMbLCHKuN61NZlts+LEctfwoya43RtcubqMc7eKw4k0JnnoYgB" + "ocLXOtloCb7jfubOsnfORvrUkK0+Ne6anRhFBYfaBmGU75cQgwADBQP/XxR2" + "qGHiwn+0YiMioRDRiIAxp6UiC/JQIri2AKSqAi0zeAMdrRsBN7kyzYVVpWwN" + "5u13gPdQ2HnJ7d4wLWAuizUdKIQxBG8VoCxkbipnwh2RR4xCXFDhJrJFQUm+" + "4nKx9JvAmZTBIlI5Wsi5qxst/9p5MgP3flXsNi1tRbTmRhqIRgQYEQIABgUC" + "QBHyOAAKCRAOtk6iUOgnkBStAJoCZBVM61B1LG2xip294MZecMtCwQCbBbsk" + "JVCXP0/Szm05GB+WN+MOCT2wAgAA"); PgpPublicKeyRing pgpPub = new PgpPublicKeyRing(testPubKeyRing); var pubKey = pgpPub.GetPublicKey(); Assert.AreEqual(0, pubKey.KeyCertifications.Count); var firstUserId = pubKey.GetUserIds().FirstOrDefault(); Assert.NotNull(firstUserId); Assert.AreEqual(1, firstUserId.SelfCertifications.Count); Assert.AreEqual(0, firstUserId.OtherCertifications.Count); Assert.AreEqual(0, firstUserId.RevocationSignatures.Count); Assert.AreEqual(PgpSignatureType.PositiveCertification, firstUserId.SelfCertifications[0].Signature.SignatureType); var newPubKey = PgpPublicKey.RemoveCertification(pubKey, firstUserId, firstUserId.SelfCertifications[0]); firstUserId = newPubKey.GetUserIds().FirstOrDefault(); Assert.NotNull(firstUserId); Assert.AreEqual(0, firstUserId.SelfCertifications.Count); Assert.AreEqual(0, firstUserId.OtherCertifications.Count); Assert.AreEqual(0, firstUserId.RevocationSignatures.Count); }
public static PgpPublicKeyRingBundle RemovePublicKeyRing(PgpPublicKeyRingBundle bundle, PgpPublicKeyRing publicKeyRing) { long keyId = publicKeyRing.GetPublicKey().KeyId; if (!bundle.pubRings.Contains(keyId)) { throw new ArgumentException("Bundle does not contain a key with a keyId for the passed in ring."); } IDictionary dictionary = Platform.CreateHashtable(bundle.pubRings); IList list = Platform.CreateArrayList(bundle.order); dictionary.Remove(keyId); list.Remove(keyId); return(new PgpPublicKeyRingBundle(dictionary, list)); }
public PgpPublicKeyRingBundle(IEnumerable e) { pubRings = Platform.CreateHashtable(); order = Platform.CreateArrayList(); foreach (object item in e) { PgpPublicKeyRing pgpPublicKeyRing = item as PgpPublicKeyRing; if (pgpPublicKeyRing == null) { throw new PgpException(Platform.GetTypeName(item) + " found where PgpPublicKeyRing expected"); } long keyId = pgpPublicKeyRing.GetPublicKey().KeyId; pubRings.Add(keyId, pgpPublicKeyRing); order.Add(keyId); } }
private PgpSecretKey FindSuitableKeyForEncryption() { var pgpPub = new PgpPublicKeyRing(testPubKeyRing); var pubKey = pgpPub.GetPublicKey(); var sKey = new PgpSecretKeyRing(testPrivKeyRing); long pgpKeyID = 0; foreach (PgpPublicKey pgpKey in pgpPub.GetPublicKeys()) { if (pgpKey.IsEncryptionKey) { pgpKeyID = pgpKey.KeyId; } } return(sKey.GetSecretKey(pgpKeyID)); }
private void DoBasicKeyRingCheck(PgpPublicKeyRing pubKeyRing) { foreach (PgpPublicKey pubKey in pubKeyRing.GetPublicKeys()) { if (pubKey.IsMasterKey) { if (pubKey.IsEncryptionKey) { Fail("master key showed as encryption key!"); } } else { if (!pubKey.IsEncryptionKey) { Fail("sub key not encryption key!"); } foreach (PgpSignature certification in pubKeyRing.GetPublicKey().GetSignatures()) { certification.InitVerify(pubKeyRing.GetPublicKey()); if (!certification.VerifyCertification((string)First(pubKeyRing.GetPublicKey().GetUserIds()), pubKeyRing.GetPublicKey())) { Fail("subkey certification does not verify"); } } } } }
private void DoTestSignedEncMessage() { PgpObjectFactory pgpFact = new PgpObjectFactory(signedEncMessage); PgpEncryptedDataList encList = (PgpEncryptedDataList)pgpFact.NextPgpObject(); PgpPublicKeyEncryptedData encP = (PgpPublicKeyEncryptedData)encList[0]; PgpPublicKeyRing publicKeyRing = new PgpPublicKeyRing(testPubKey); PgpPublicKey publicKey = publicKeyRing.GetPublicKey(encP.KeyId); PgpSecretKey secretKey = PgpSecretKey.ParseSecretKeyFromSExpr(new MemoryStream(sExprKeySub, false), "test".ToCharArray(), publicKey); Stream clear = encP.GetDataStream(secretKey.ExtractPrivateKey(null)); PgpObjectFactory plainFact = new PgpObjectFactory(clear); PgpCompressedData cData = (PgpCompressedData)plainFact.NextPgpObject(); PgpObjectFactory compFact = new PgpObjectFactory(cData.GetDataStream()); PgpOnePassSignatureList sList = (PgpOnePassSignatureList)compFact.NextPgpObject(); PgpOnePassSignature ops = sList[0]; PgpLiteralData lData = (PgpLiteralData)compFact.NextPgpObject(); if (!"test.txt".Equals(lData.FileName)) { Fail("wrong file name detected"); } Stream dIn = lData .GetInputStream(); ops.InitVerify(publicKeyRing.GetPublicKey(ops.KeyId)); int ch; while ((ch = dIn.ReadByte()) >= 0) { ops.Update((byte)ch); } PgpSignatureList p3 = (PgpSignatureList)compFact.NextPgpObject(); if (!ops.Verify(p3[0])) { Fail("Failed signature check"); } }
private void CheckEccKey(IPgpSecretKeyRing secretKeyRing) { var keyCount = 0; var bytes = secretKeyRing.GetEncoded(); var pgpSec2 = new PgpSecretKeyRing(bytes); foreach (PgpSecretKey k in pgpSec2.GetSecretKeys()) { keyCount++; var pk = k.PublicKey; pk.GetSignatures(); var pkBytes = pk.GetEncoded(); var pkR1 = new PgpPublicKeyRing(pkBytes); Assert.IsNotNull(pkR1); var pk1 = pkR1.GetPublicKey(); AreEqual(pk1.GetFingerprint(), pk.GetFingerprint()); var pkBytes1 = pkR1.GetEncoded(); var pkR2 = new PgpPublicKeyRing(pkBytes1); Assert.IsNotNull(pkR2); var pkBytes2 = pkR2.GetEncoded(); AreEqual(pkBytes1, pkBytes2); } if (keyCount != secretKeyRing.SecretKeyCount) { Fail("wrong number of secret keys"); } }
public override void PerformTest() { // // Read the public key // PgpPublicKeyRing pubKeyRing = new PgpPublicKeyRing(testPubKey); foreach (PgpSignature certification in pubKeyRing.GetPublicKey().GetSignatures()) { certification.InitVerify(pubKeyRing.GetPublicKey()); if (!certification.VerifyCertification((string)First(pubKeyRing.GetPublicKey().GetUserIds()), pubKeyRing.GetPublicKey())) { Fail("self certification does not verify"); } } if (pubKeyRing.GetPublicKey().BitStrength != 256) { Fail("incorrect bit strength returned"); } // // Read the private key // PgpSecretKeyRing secretKeyRing = new PgpSecretKeyRing(testPrivKey); PgpPrivateKey privKey = secretKeyRing.GetSecretKey().ExtractPrivateKey(testPasswd); GenerateAndSign(); // // sExpr // byte[] msg = Encoding.ASCII.GetBytes("hello world!"); PgpSecretKey key = PgpSecretKey.ParseSecretKeyFromSExpr(new MemoryStream(sExprKey, false), "test".ToCharArray()); PgpSignatureGenerator signGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.ECDsa, HashAlgorithmTag.Sha256); signGen.InitSign(PgpSignature.BinaryDocument, key.ExtractPrivateKey(null)); signGen.Update(msg); PgpSignature sig = signGen.Generate(); sig.InitVerify(key.PublicKey); sig.Update(msg); if (!sig.Verify()) { Fail("signature failed to verify!"); } }
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"); } }
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"); } }
private void ExistingEmbeddedJpegTest() { PgpPublicKeyRing pgpPub = new PgpPublicKeyRing(embeddedJPEGKey); PgpPublicKey pubKey = pgpPub.GetPublicKey(); int count = 0; foreach (PgpUserAttributeSubpacketVector attributes in pubKey.GetUserAttributes()) { int sigCount = 0; foreach (PgpSignature sig in pubKey.GetSignaturesForUserAttribute(attributes)) { sig.InitVerify(pubKey); if (!sig.VerifyCertification(attributes, pubKey)) { Fail("signature failed verification"); } sigCount++; } if (sigCount != 1) { Fail("Failed user attributes signature check"); } count++; } if (count != 1) { Fail("didn't find user attributes"); } }
private void FingerPrintTest() { // // version 3 // PgpPublicKeyRing pgpPub = new PgpPublicKeyRing(fingerprintKey); PgpPublicKey pubKey = pgpPub.GetPublicKey(); if (!Arrays.AreEqual(pubKey.GetFingerprint(), Hex.Decode("4FFB9F0884266C715D1CEAC804A3BBFA"))) { Fail("version 3 fingerprint test failed"); } // // version 4 // pgpPub = new PgpPublicKeyRing(testPubKey); pubKey = pgpPub.GetPublicKey(); if (!Arrays.AreEqual(pubKey.GetFingerprint(), Hex.Decode("3062363c1046a01a751946bb35586146fdf3f373"))) { Fail("version 4 fingerprint test failed"); } }
public override void PerformTest() { // // Read the public key // PgpPublicKeyRing pgpPub = new PgpPublicKeyRing(testPubKey); var pubKey = pgpPub.GetPublicKey(); // // Read the private key // PgpSecretKeyRing sKey = new PgpSecretKeyRing(testPrivKey); IPgpSecretKey secretKey = sKey.GetSecretKey(); IPgpPrivateKey pgpPrivKey = secretKey.ExtractPrivateKey(pass); // // 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(pubKey); 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"); } // // signature generation // GenerateTest(sKey, pubKey, pgpPrivKey); // // signature generation - canonical text // const string data = "hello world!"; byte[] dataBytes = Encoding.ASCII.GetBytes(data); MemoryStream bOut = new MemoryStream(); MemoryStream testIn = new MemoryStream(dataBytes, false); PgpSignatureGenerator sGen = new PgpSignatureGenerator( PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1); sGen.InitSign(PgpSignature.CanonicalTextDocument, 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.Text, "_CONSOLE", dataBytes.Length, testDateTime); while ((ch = testIn.ReadByte()) >= 0) { lOut.WriteByte((byte) ch); sGen.Update((byte)ch); } lGen.Close(); sGen.Generate().Encode(bcOut); cGen.Close(); // // verify Generated signature - canconical text // 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(pubKey); while ((ch = dIn.ReadByte()) >= 0) { ops.Update((byte)ch); } p3 = (PgpSignatureList) pgpFact.NextPgpObject(); if (!ops.Verify(p3[0])) { Fail("Failed generated signature check"); } // // Read the public key with user attributes // pgpPub = new PgpPublicKeyRing(testPubWithUserAttr); pubKey = pgpPub.GetPublicKey(); int count = 0; foreach (PgpUserAttributeSubpacketVector attributes in pubKey.GetUserAttributes()) { int sigCount = 0; foreach (object sigs in pubKey.GetSignaturesForUserAttribute(attributes)) { if (sigs == null) Fail("null signature found"); sigCount++; } if (sigCount != 1) { Fail("Failed user attributes signature check"); } count++; } if (count != 1) { Fail("Failed user attributes check"); } byte[] pgpPubBytes = pgpPub.GetEncoded(); pgpPub = new PgpPublicKeyRing(pgpPubBytes); pubKey = pgpPub.GetPublicKey(); count = 0; foreach (object ua in pubKey.GetUserAttributes()) { if (ua == null) Fail("null user attribute found"); count++; } if (count != 1) { Fail("Failed user attributes reread"); } // // reading test extra data - key with edge condition for DSA key password. // char[] passPhrase = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; sKey = new PgpSecretKeyRing(testPrivKey2); pgpPrivKey = sKey.GetSecretKey().ExtractPrivateKey(passPhrase); // // reading test - aes256 encrypted passphrase. // sKey = new PgpSecretKeyRing(aesSecretKey); pgpPrivKey = sKey.GetSecretKey().ExtractPrivateKey(pass); // // reading test - twofish encrypted passphrase. // sKey = new PgpSecretKeyRing(twofishSecretKey); pgpPrivKey = sKey.GetSecretKey().ExtractPrivateKey(pass); // // use of PgpKeyPair // DsaParametersGenerator pGen = new DsaParametersGenerator(); pGen.Init(512, 80, new SecureRandom()); // TODO Is the certainty okay? DsaParameters dsaParams = pGen.GenerateParameters(); DsaKeyGenerationParameters kgp = new DsaKeyGenerationParameters(new SecureRandom(), dsaParams); IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator("DSA"); kpg.Init(kgp); IAsymmetricCipherKeyPair kp = kpg.GenerateKeyPair(); PgpKeyPair pgpKp = new PgpKeyPair(PublicKeyAlgorithmTag.Dsa, kp.Public, kp.Private, DateTime.UtcNow); PgpPublicKey k1 = pgpKp.PublicKey; PgpPrivateKey k2 = pgpKp.PrivateKey; }
private void LongSubPacketsTest() { Stream fIn = SimpleTest.GetTestDataAsStream("openpgp.longSigSubPack.asc"); Stream bIn = new BufferedStream(fIn); PgpPublicKeyRing pkr = new PgpPublicKeyRing(PgpUtilities.GetDecoderStream(bIn)); bIn.Close(); PgpPublicKey masterpk = pkr.GetPublicKey(); // Check userids foreach (string uid in masterpk.GetUserIds()) { CheckUidSig(masterpk, uid); } }