예제 #1
0
파일: DSA2Test.cs 프로젝트: 894880010/MP
        private void doSigVerifyTest(
            string publicKeyFile,
            string sigFile)
        {
            PgpPublicKeyRing publicKey = loadPublicKey(publicKeyFile);
            PgpObjectFactory pgpFact   = loadSig(sigFile);

            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(publicKey.GetPublicKey());

            int ch;

            while ((ch = dIn.ReadByte()) >= 0)
            {
                ops.Update((byte)ch);
            }

            PgpSignatureList p3 = (PgpSignatureList)pgpFact.NextPgpObject();

            Assert.IsTrue(ops.Verify(p3[0]));
        }
예제 #2
0
        internal OpenPgpDigitalCertificate(PgpPublicKeyRing keyring, PgpPublicKey pubkey)
        {
            var bytes   = pubkey.GetFingerprint();
            var builder = new StringBuilder();

            for (int i = 0; i < bytes.Length; i++)
            {
                builder.Append(bytes[i].ToString("X2"));
            }

//			var trust = pubkey.GetTrustData ();
//			if (trust != null) {
//				TrustLevel = (TrustLevel) (trust[0] & 15);
//			} else {
//				TrustLevel = TrustLevel.None;
//			}

            Fingerprint = builder.ToString();
            PublicKey   = pubkey;
            KeyRing     = keyring;

            if (!UpdateUserId(pubkey) && !pubkey.IsMasterKey)
            {
                foreach (PgpPublicKey key in keyring.GetPublicKeys())
                {
                    if (key.IsMasterKey)
                    {
                        UpdateUserId(key);
                        break;
                    }
                }
            }
        }
예제 #3
0
        private void DoTestEncMessage()
        {
            PgpObjectFactory pgpFact = new PgpObjectFactory(encMessage);

            PgpEncryptedDataList encList = (PgpEncryptedDataList)pgpFact.NextPgpObject();

            PgpPublicKeyEncryptedData encP = (PgpPublicKeyEncryptedData)encList[0];

            PgpPublicKey publicKey = new PgpPublicKeyRing(testPubKey).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());

            PgpLiteralData lData = (PgpLiteralData)compFact.NextPgpObject();

            if (!"test.txt".Equals(lData.FileName))
            {
                Fail("wrong file name detected");
            }
        }
예제 #4
0
        public static GPGKey AsciiArmored2GPGKey(string asciiArmored)
        {
            GPGKey key = null;

            using (var s = GenerateStreamFromString(asciiArmored)) {
                var pgpPub = new PgpPublicKeyRing(PgpUtilities.GetDecoderStream(s));
                var pubKey = pgpPub.GetPublicKey();
                key = new GPGKey {
                    Id = null,
                    FullFingerPrint        = pubKey.GetFingerprint().ToHexString(),
                    AsciiArmoredPublicKey  = asciiArmored,
                    AsciiArmoredPrivateKey = null,
                    Emails  = new List <string>(),
                    Names   = new List <string>(),
                    KeyUids = new List <GPGKeyUid>(),
                    KeyBits = pubKey.BitStrength,
                };

                foreach (string userId in pubKey.GetUserIds())
                {
                    var m     = NameObsEmailGPGReg.Match(userId);
                    var m2    = NameEmailGPGReg.Match(userId);
                    var email = "";
                    var name  = "";
                    var obs   = "";
                    if (m.Success && m.Groups.Count == 4)
                    {
                        email = m.Groups[3].Value.Trim();
                        obs   = m.Groups[2].Value.Trim();
                        key.Emails.Add(email);
                        var z = NameObsGPGReg.Match(m.Groups[1].Value);
                        if (z.Success && z.Groups.Count == 3)
                        {
                            name = z.Groups[1].Value;
                            obs  = z.Groups[2].Value;
                            key.Names.Add(name);
                        }
                    }
                    else if (m2.Success && m2.Groups.Count == 3)
                    {
                        name  = m2.Groups[1].Value;
                        email = m2.Groups[2].Value;
                        key.Names.Add(name);
                        key.Emails.Add(email);
                    }
                    else
                    {
                        name = userId;
                        key.Names.Add(name);
                    }

                    key.KeyUids.Add(new GPGKeyUid {
                        Name        = name,
                        Email       = email,
                        Description = obs,
                    });
                }
            }
            return(key);
        }
예제 #5
0
        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));
        }
예제 #6
0
        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);
        }
예제 #7
0
        public void Generate()
        {
            // Master/Signing key
            var ecdsa = ECDsa.Create(ECCurve.NamedCurves.nistP256);
            // Encryption key
            var ecdh = ECDiffieHellman.Create(ECCurve.NamedCurves.nistP256);

            // Generate a key ring
            var passPhrase = "test";
            PgpKeyRingGenerator keyRingGen = new PgpKeyRingGenerator(ecdsa, "*****@*****.**", passPhrase);

            keyRingGen.AddSubKey(ecdh);

            PgpPublicKeyRing pubRing = keyRingGen.GeneratePublicKeyRing();

            // TODO: add check of KdfParameters
            DoBasicKeyRingCheck(pubRing);

            PgpSecretKeyRing secRing = keyRingGen.GenerateSecretKeyRing();

            PgpPublicKeyRing pubRingEnc = new PgpPublicKeyRing(pubRing.GetEncoded());

            Assert.That(pubRing.GetEncoded(), Is.EqualTo(pubRingEnc.GetEncoded()), "public key ring encoding failed");

            PgpSecretKeyRing secRingEnc = new PgpSecretKeyRing(secRing.GetEncoded());

            Assert.That(secRing.GetEncoded(), Is.EqualTo(secRingEnc.GetEncoded()), "secret key ring encoding failed");

            PgpPrivateKey pgpPrivKey = secRing.GetSecretKey().ExtractPrivateKey(passPhrase);
        }
예제 #8
0
        internal GenericAPI(RoamingNetwork RoamingNetwork,
                            String HTTPServerName = DefaultHTTPServerName,
                            IPPort HTTPServerPort = null,
                            String URIPrefix      = "",
                            Func <String, Stream> GetRessources = null,

                            String ServiceName                = DefaultHTTPServerName,
                            EMailAddress APIEMailAddress      = null,
                            PgpPublicKeyRing APIPublicKeyRing = null,
                            PgpSecretKeyRing APISecretKeyRing = null,
                            String APIPassphrase              = null,
                            EMailAddressList APIAdminEMail    = null,
                            SMTPClient APISMTPClient          = null,

                            DNSClient DNSClient = null,
                            String LogfileName  = DefaultLogfileName)

            : this(RoamingNetwork,
                   new HTTPServer(DefaultServerName : DefaultHTTPServerName).AttachTCPPorts(HTTPServerPort != null ? HTTPServerPort : DefaultHTTPServerPort),
                   URIPrefix,
                   GetRessources,

                   ServiceName,
                   APIEMailAddress,
                   APIPublicKeyRing,
                   APISecretKeyRing,
                   APIPassphrase,
                   APIAdminEMail,
                   APISMTPClient,

                   LogfileName)

        {
        }
예제 #9
0
        /// <summary>
        /// Initialize the OCPI HTTP server using IPAddress.Any, http port 8080 and maybe start the server.
        /// </summary>
        internal GenericAPI(RoamingNetwork RoamingNetwork,
                            HTTPServer HTTPServer,
                            String URIPrefix = "/ext/OCPI",
                            Func <String, Stream> GetRessources = null,

                            String ServiceName                = DefaultHTTPServerName,
                            EMailAddress APIEMailAddress      = null,
                            PgpPublicKeyRing APIPublicKeyRing = null,
                            PgpSecretKeyRing APISecretKeyRing = null,
                            String APIPassphrase              = null,
                            EMailAddressList APIAdminEMail    = null,
                            SMTPClient APISMTPClient          = null,

                            String LogfileName = DefaultLogfileName)

        {
            #region Initial checks

            if (RoamingNetwork == null)
            {
                throw new ArgumentNullException("RoamingNetwork", "The given parameter must not be null!");
            }

            if (HTTPServer == null)
            {
                throw new ArgumentNullException("HTTPServer", "The given parameter must not be null!");
            }

            if (URIPrefix.IsNullOrEmpty())
            {
                throw new ArgumentNullException("URIPrefix", "The given parameter must not be null or empty!");
            }

            if (!URIPrefix.StartsWith("/"))
            {
                URIPrefix = "/" + URIPrefix;
            }

            #endregion

            #region Init data

            this._HTTPServer    = HTTPServer;
            this._GetRessources = GetRessources;
            this._URIPrefix     = URIPrefix;

            this._ServiceName      = ServiceName;
            this._APIEMailAddress  = APIEMailAddress;
            this._APIPublicKeyRing = APIPublicKeyRing;
            this._APISecretKeyRing = APISecretKeyRing;
            this._APIPassphrase    = APIPassphrase;
            this._APIAdminEMail    = APIAdminEMail;
            this._APISMTPClient    = APISMTPClient;

            this._DNSClient = HTTPServer.DNSClient;

            #endregion

            RegisterURITemplates();
        }
예제 #10
0
        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);
        }
예제 #11
0
        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");
                        }
                    }
                }
            }
        }
예제 #12
0
        public void FingerPrintTest()
        {
            //
            // version 3
            //
            PgpPublicKeyRing pgpPub = new PgpPublicKeyRing(fingerprintKey);

            PgpPublicKey pubKey = pgpPub.GetPublicKey();

            /*if (!AreEqual(pubKey.GetFingerprint(), Hex.Decode("4FFB9F0884266C715D1CEAC804A3BBFA")))
             * {
             *  Fail("version 3 fingerprint test failed");
             * }*/

            //
            // version 4
            //
            pgpPub = new PgpPublicKeyRing(testPubKey);

            pubKey = pgpPub.GetPublicKey();

            /*if (!AreEqual(pubKey.GetFingerprint(), Hex.Decode("3062363c1046a01a751946bb35586146fdf3f373")))
             * {
             * Fail("version 4 fingerprint test failed");
             * }*/
        }
예제 #13
0
        public void EmbeddedJpegTest()
        {
            PgpPublicKeyRing pgpPub = new PgpPublicKeyRing(testPubKey);
            PgpSecretKeyRing pgpSec = new PgpSecretKeyRing(testPrivKey);

            PgpPublicKey pubKey = pgpPub.GetPublicKey();

            PgpUserAttributes vGen = new PgpUserAttributes();

            vGen.JpegImageAttribute = jpegImage;

            var certification = PgpCertification.GenerateUserCertification(
                PgpSignatureType.PositiveCertification,
                pubKey,
                pgpSec.GetSecretKey().ExtractPrivateKey(pass),
                vGen,
                pubKey);

            PgpPublicKey nKey = PgpPublicKey.AddCertification(pubKey, vGen, certification);

            int count = 0;

            foreach (PgpUser user in nKey.GetUserAttributes())
            {
                Assert.AreEqual(1, user.SelfCertifications.Count);
                Assert.IsTrue(user.SelfCertifications[0].Verify());
                count++;
            }

            Assert.AreEqual(1, count);

            nKey = PgpPublicKey.RemoveCertification(nKey, vGen);
            Assert.IsFalse(nKey.GetUserAttributes().Any());
        }
예제 #14
0
        public void DoTestMasterKey()
        {
            PgpSecretKey key       = PgpSecretKey.ParseSecretKeyFromSExpr(new MemoryStream(sExprKeyMaster, false), "test");
            PgpPublicKey publicKey = new PgpPublicKeyRing(testPubKey).GetPublicKey();

            KeyTestHelper.SignAndVerifyTestMessage(key.ExtractPrivateKey(""), publicKey);
        }
예제 #15
0
        //[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()));
        }
예제 #16
0
        internal PgpKeyRingBundle(IEnumerable e)
        {
            this.secretRings = Platform.CreateHashtable();
            this.pubRings    = Platform.CreateHashtable();

            this.order = Platform.CreateArrayList();

            foreach (object obj in e)
            {
                if (obj is PgpSecretKeyRing)
                {
                    PgpSecretKeyRing pgpSecret = obj as PgpSecretKeyRing;
                    long             key       = pgpSecret.GetPublicKey().KeyId;
                    secretRings.Add(key, pgpSecret);
                    order.Add(key);
                }
                else if (obj is PgpPublicKeyRing)
                {
                    PgpPublicKeyRing pgpPub = obj as PgpPublicKeyRing;
                    long             key    = pgpPub.GetPublicKey().KeyId;
                    pubRings.Add(key, pgpPub);
                    order.Add(key);
                }
            }
        }
예제 #17
0
        /// <summary>
        /// Create a new e-mail address.
        /// </summary>
        /// <param name="SimpleEMailAddressString">A string representation of a simple e-mail address.</param>
        /// <param name="SecretKeyRing">The secret key ring for an e-mail address.</param>
        /// <param name="PublicKeyRing">The public key ring for an e-mail address.</param>
        public EMailAddress(String SimpleEMailAddressString,
                            PgpSecretKeyRing SecretKeyRing = null,
                            PgpPublicKeyRing PublicKeyRing = null)

            : this("", SimpleEMailAddress.Parse(SimpleEMailAddressString), SecretKeyRing, PublicKeyRing)

        {
        }
예제 #18
0
        /// <summary>
        /// Create a new e-mail address.
        /// </summary>
        /// <param name="SimpleEMailAddress">A simple e-mail address.</param>
        /// <param name="SecretKeyRing">The secret key ring for an e-mail address.</param>
        /// <param name="PublicKeyRing">The public key ring for an e-mail address.</param>
        public EMailAddress(SimpleEMailAddress SimpleEMailAddress,
                            PgpSecretKeyRing SecretKeyRing = null,
                            PgpPublicKeyRing PublicKeyRing = null)

            : this("", SimpleEMailAddress, SecretKeyRing, PublicKeyRing)

        {
        }
예제 #19
0
 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);
     }
 }
예제 #20
0
        public void ReferenceTest()
        {
            var pubKeyRing = new PgpPublicKeyRing(referencePubKey);
            var publicKey  = pubKeyRing.GetPublicKey();
            var signature  = new PgpSignature(referenceSignature);

            Assert.IsTrue(signature.Verify(publicKey, new MemoryStream(Encoding.ASCII.GetBytes(referenceMessage), false)), "signature failed to verify!");
        }
예제 #21
0
        private void Generate()
        {
            SecureRandom random = SecureRandom.GetInstance("SHA1PRNG");

            //
            // Generate a master key
            //
            IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator("ECDSA");

            keyGen.Init(new ECKeyGenerationParameters(SecObjectIdentifiers.SecP256r1, random));

            AsymmetricCipherKeyPair kpSign = keyGen.GenerateKeyPair();

            PgpKeyPair ecdsaKeyPair = new PgpKeyPair(PublicKeyAlgorithmTag.ECDsa, kpSign, DateTime.UtcNow);

            //
            // Generate an encryption key
            //
            keyGen = GeneratorUtilities.GetKeyPairGenerator("ECDH");
            keyGen.Init(new ECKeyGenerationParameters(SecObjectIdentifiers.SecP256r1, random));

            AsymmetricCipherKeyPair kpEnc = keyGen.GenerateKeyPair();

            PgpKeyPair ecdhKeyPair = new PgpKeyPair(PublicKeyAlgorithmTag.ECDH, kpEnc, DateTime.UtcNow);

            //
            // Generate a key ring
            //
            char[] passPhrase = "test".ToCharArray();
            PgpKeyRingGenerator keyRingGen = new PgpKeyRingGenerator(PgpSignature.PositiveCertification, ecdsaKeyPair,
                                                                     "*****@*****.**", SymmetricKeyAlgorithmTag.Aes256, passPhrase, true, null, null, random);

            keyRingGen.AddSubKey(ecdhKeyPair);

            PgpPublicKeyRing pubRing = keyRingGen.GeneratePublicKeyRing();

            // TODO: add check of KdfParameters
            DoBasicKeyRingCheck(pubRing);

            PgpSecretKeyRing secRing = keyRingGen.GenerateSecretKeyRing();

            PgpPublicKeyRing pubRingEnc = new PgpPublicKeyRing(pubRing.GetEncoded());

            if (!Arrays.AreEqual(pubRing.GetEncoded(), pubRingEnc.GetEncoded()))
            {
                Fail("public key ring encoding failed");
            }

            PgpSecretKeyRing secRingEnc = new PgpSecretKeyRing(secRing.GetEncoded());

            if (!Arrays.AreEqual(secRing.GetEncoded(), secRingEnc.GetEncoded()))
            {
                Fail("secret key ring encoding failed");
            }

            PgpPrivateKey pgpPrivKey = secRing.GetSecretKey().ExtractPrivateKey(passPhrase);
        }
예제 #22
0
        /// <summary>
        /// Imports a public pgp keyring.
        /// </summary>
        /// <remarks>
        /// Imports a public pgp keyring.
        /// </remarks>
        /// <param name="keyring">The pgp keyring.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <paramref name="keyring"/> is <c>null</c>.
        /// </exception>
        public virtual void Import(PgpPublicKeyRing keyring)
        {
            if (keyring == null)
            {
                throw new ArgumentNullException(nameof(keyring));
            }

            PublicKeyRingBundle = PgpPublicKeyRingBundle.AddPublicKeyRing(PublicKeyRingBundle, keyring);
            SavePublicKeyRingBundle();
        }
예제 #23
0
        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());
        }
예제 #24
0
        public static void GenerateKeyPair(string userid, string password, out PgpPublicKeyRing pkr, out PgpSecretKeyRing skr)
        {
            PgpKeyRingGenerator krgen = PGP.generateKeyRingGenerator(userid, password);

            // Generate public key ring, dump to file.
            pkr = krgen.GeneratePublicKeyRing();

            // Generate private key, dump to file.
            skr = krgen.GenerateSecretKeyRing();
        }
예제 #25
0
        //[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()));
        }
예제 #26
0
        /// <summary>
        /// Create a new e-mail address.
        /// </summary>
        /// <param name="OwnerName">The name of the owner of the e-mail address.</param>
        /// <param name="SimpleEMailAddress">A simple e-mail address.</param>
        /// <param name="SecretKeyRing">The secret key ring for an e-mail address.</param>
        /// <param name="PublicKeyRing">The public key ring for an e-mail address.</param>
        public EMailAddress(String OwnerName,
                            SimpleEMailAddress SimpleEMailAddress,
                            PgpSecretKeyRing SecretKeyRing = null,
                            PgpPublicKeyRing PublicKeyRing = null)

        {
            this._OwnerName     = OwnerName.Trim();
            this._Address       = SimpleEMailAddress;
            this._PublicKeyRing = PublicKeyRing;
            this._SecretKeyRing = SecretKeyRing;
        }
    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 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);
        }
    }
예제 #29
0
 /// <summary>
 /// Returns public key from armored ASCII key content.
 /// </summary>
 /// <param name="key">Armored text format containing key.</param>
 /// <returns></returns>
 public static PgpPublicKey GetPublicKeyFromAsciiArmored(string key)
 {
     using (var memStream = new MemoryStream(Encoding.UTF8.GetBytes(key)))
     {
         using (var armored = new ArmoredInputStream(memStream))
         {
             var result = new PgpPublicKeyRing(armored);
             return(result.GetPublicKey());
         }
     }
 }
예제 #30
0
        public static void p5_crypto_pgp_keys_create(ApplicationContext context, ActiveEventArgs e)
        {
            // Making sure we clean up after ourselves.
            using (new ArgsRemover(e.Args, true)) {
                // Retrieving identity (normally a name + email address), in addition to password.
                string identity = e.Args.GetExChildValue <string> ("identity", context);
                string password = e.Args.GetExChildValue <string> ("password", context);
                if (string.IsNullOrEmpty(identity) || string.IsNullOrEmpty(password))
                {
                    throw new LambdaException(
                              "Minimum [identity] and [password] needs to be supplied to create a PGP keypair",
                              e.Args,
                              context);
                }

                // Retrieving other parameters to PGP keypair creation, giving them sane defaults if not supplied.
                DateTime expires        = e.Args.GetExChildValue("expires", context, DateTime.Now.AddYears(3));
                int      strength       = e.Args.GetExChildValue <int> ("strength", context, 4096);
                long     publicExponent = e.Args.GetExChildValue("public-exponent", context, 65537L);
                int      certainty      = e.Args.GetExChildValue("certainty", context, 5);

                // Creating our key generator.
                PgpKeyRingGenerator generator = GetKeyRingGenerator(
                    context,
                    identity,
                    password,
                    expires,
                    strength,
                    publicExponent,
                    certainty);

                // Generating public keyrign.
                PgpPublicKeyRing publicRing = generator.GeneratePublicKeyRing();

                // Generating secret keyring. "Secret key" is BC's name for private key.
                PgpSecretKeyRing secretRing = generator.GenerateSecretKeyRing();

                /*
                 * Retrieving PGP context to let MimeKit import keys into PGP storage.
                 * Making sure we retrieve it in "write mode".
                 */
                using (var ctx = context.RaiseEvent(".p5.crypto.pgp-keys.context.create", new Node("", true)).Get <OpenPgpContext> (context)) {
                    // Saves public keyring.
                    ctx.Import(publicRing);

                    // Saves secret keyring (private key, BC uses different naming convention).
                    ctx.Import(secretRing);
                }

                // Returning fingerprint and key-id to caller.
                e.Args.Add("fingerprint", Fingerprint.FingerprintString(publicRing.GetPublicKey().GetFingerprint()));
                e.Args.Add("key-id", ((int)publicRing.GetPublicKey().KeyId).ToString("X"));
            }
        }
예제 #31
0
        private void DoTestMasterKey()
        {
            PgpSecretKey key = PgpSecretKey.ParseSecretKeyFromSExpr(new MemoryStream(sExprKeyMaster, false),
                "test".ToCharArray());

            byte[] msg = Encoding.UTF8.GetBytes("hello world!");

            PgpSignatureGenerator signGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.ECDsa, HashAlgorithmTag.Sha256);
            signGen.InitSign(PgpSignature.BinaryDocument, key.ExtractPrivateKey(null));
            signGen.Update(msg);
            PgpSignature sig = signGen.Generate();

            PgpPublicKey publicKey = new PgpPublicKeyRing(testPubKey).GetPublicKey();
            sig.InitVerify(publicKey);
            sig.Update(msg);

            if (!sig.Verify())
            {
                Fail("signature failed to verify!");
            }
        }
예제 #32
0
        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 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;
        }
예제 #34
0
        private void checkPublicKeyRingWithX509(
			byte[] keyRing)
        {
            PgpPublicKeyRing pubRing = new PgpPublicKeyRing(keyRing);
            IEnumerator en = pubRing.GetPublicKeys().GetEnumerator();

            if (en.MoveNext())
            {
                PgpPublicKey key = (PgpPublicKey) en.Current;

                IEnumerator sEn = key.GetSignatures().GetEnumerator();

                if (sEn.MoveNext())
                {
                    PgpSignature sig = (PgpSignature) sEn.Current;
                    if (sig.KeyAlgorithm != PublicKeyAlgorithmTag.Experimental_1)
                    {
                        Fail("experimental signature not found");
                    }
                    if (!AreEqual(sig.GetSignature(), Hex.Decode("000101")))
                    {
                        Fail("experimental encoding check failed");
                    }
                }
                else
                {
                    Fail("no signature found");
                }
            }
            else
            {
                Fail("no key found");
            }
        }
예제 #35
0
        public void PublicKeyRingWithX509Test()
        {
            checkPublicKeyRingWithX509(pubWithX509);

            PgpPublicKeyRing pubRing = new PgpPublicKeyRing(pubWithX509);

            checkPublicKeyRingWithX509(pubRing.GetEncoded());
        }
예제 #36
0
        public void PerformTest8()
        {
            PgpPublicKeyRingBundle pubRings = new PgpPublicKeyRingBundle(pub8);

            int count = 0;

            byte[] encRing = pubRings.GetEncoded();

            pubRings = new PgpPublicKeyRingBundle(encRing);

            foreach (PgpPublicKeyRing pgpPub1 in pubRings.GetKeyRings())
            {
                count++;

                int keyCount = 0;

                byte[] bytes = pgpPub1.GetEncoded();

                PgpPublicKeyRing pgpPub2 = new PgpPublicKeyRing(bytes);

                foreach (PgpPublicKey o in pgpPub2.GetPublicKeys())
                {
                    if (o == null)
                        Fail("null key found");

                    keyCount++;
                }

                if (keyCount != 2)
                {
                    Fail("wrong number of public keys");
                }
            }

            if (count != 2)
            {
                Fail("wrong number of public keyrings");
            }

            PgpSecretKeyRingBundle secretRings1 = new PgpSecretKeyRingBundle(sec8);

            count = 0;

            encRing = secretRings1.GetEncoded();

            PgpSecretKeyRingBundle secretRings2 = new PgpSecretKeyRingBundle(encRing);

            foreach (PgpSecretKeyRing pgpSec1 in secretRings1.GetKeyRings())
            {
                count++;

                int keyCount = 0;

                byte[] bytes = pgpSec1.GetEncoded();

                PgpSecretKeyRing pgpSec2 = new PgpSecretKeyRing(bytes);

                foreach (PgpSecretKey k in pgpSec2.GetSecretKeys())
                {
                    keyCount++;
                    k.ExtractPrivateKey(sec8pass);
                }

                if (keyCount != 2)
                {
                    Fail("wrong number of secret keys");
                }
            }

            if (count != 1)
            {
                Fail("wrong number of secret keyrings");
            }
        }
예제 #37
0
        public void PerformTest7()
        {
            PgpPublicKeyRing pgpPub = new PgpPublicKeyRing(pub7);
            PgpPublicKey masterKey = null;

            foreach (PgpPublicKey k in pgpPub.GetPublicKeys())
            {
                if (k.IsMasterKey)
                {
                    masterKey = k;
                    continue;
                }

                int count = 0;
                PgpSignature sig = null;

                foreach (PgpSignature sigTemp in k.GetSignaturesOfType(PgpSignature.SubkeyRevocation))
                {
                    sig = sigTemp;
                    count++;
                }

                if (count != 1)
                {
                    Fail("wrong number of revocations in test7.");
                }

                sig.InitVerify(masterKey);

                if (!sig.VerifyCertification(k))
                {
                    Fail("failed to verify revocation certification");
                }
            }
        }
예제 #38
0
        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");
            }
        }
예제 #39
0
        public void TestRevocation()
        {
            PgpPublicKeyRing pgpPub = new PgpPublicKeyRing(pub7);
            PgpPublicKey masterKey = null;

            foreach (PgpPublicKey k in pgpPub.GetPublicKeys())
            {
                if (k.IsMasterKey)
                {
                    masterKey = k;
                }
            }

            int count = 0;
            PgpSignature sig = null;
            foreach (PgpSignature pgpSig in masterKey.GetSignaturesOfType(PgpSignature.KeyRevocation))
            {
                sig = pgpSig;
                ++count;
            }

            if (count != 1)
            {
                Fail("wrong number of revocations in test7.");
            }

            sig.InitVerify(masterKey);

            if (!sig.VerifyCertification(masterKey))
            {
                Fail("failed to verify revocation certification");
            }

            pgpPub = new PgpPublicKeyRing(pub7sub);
            masterKey = null;

            foreach (PgpPublicKey k in pgpPub.GetPublicKeys())
            {
                if (k.IsMasterKey)
                {
                    masterKey = k;
                    continue;
                }

                count = 0;
                sig = null;

                foreach (PgpSignature pgpSig in k.GetSignaturesOfType(PgpSignature.SubkeyRevocation))
                {
                    sig = pgpSig;
                    ++count;
                }

                if (count != 1)
                {
                    Fail("wrong number of revocations in test7 subkey.");
                }

                if (sig.SignatureType != PgpSignature.SubkeyRevocation)
                {
                    Fail("wrong signature found");
                }

                sig.InitVerify(masterKey);

                if (!sig.VerifyCertification(masterKey, k))
                {
                    Fail("failed to verify revocation certification of subkey");
                }
            }
        }
예제 #40
0
        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);
            }
        }
예제 #41
0
        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");
            }
        }
예제 #42
0
        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!");
            }
        }
예제 #43
0
        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");
                        }
                    }
                }
            }
        }
예제 #44
0
        public override void PerformTest()
        {
            //
            // Read the public key
            //
            PgpPublicKeyRing pubKeyRing = new PgpPublicKeyRing(testPubKey);

            DoBasicKeyRingCheck(pubKeyRing);

            //
            // Read the private key
            //
            PgpSecretKeyRing secretKeyRing = new PgpSecretKeyRing(testPrivKey);

            TestDecrypt(secretKeyRing);

            EncryptDecryptTest();

            Generate();
        }
        public void PublicKeyRingWithX509Test()
        {
            CheckPublicKeyRingWithX509(_pubWithX509);

            var pubRing = new PgpPublicKeyRing(_pubWithX509);

            CheckPublicKeyRingWithX509(pubRing.GetEncoded());
        }
예제 #46
0
        private void Generate()
        {
            SecureRandom random = SecureRandom.GetInstance("SHA1PRNG");

            //
            // Generate a master key
            //
            IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator("ECDSA");
            keyGen.Init(new ECKeyGenerationParameters(SecObjectIdentifiers.SecP256r1, random));

            AsymmetricCipherKeyPair kpSign = keyGen.GenerateKeyPair();

            PgpKeyPair ecdsaKeyPair = new PgpKeyPair(PublicKeyAlgorithmTag.ECDsa, kpSign, DateTime.UtcNow);

            //
            // Generate an encryption key
            //
            keyGen = GeneratorUtilities.GetKeyPairGenerator("ECDH");
            keyGen.Init(new ECKeyGenerationParameters(SecObjectIdentifiers.SecP256r1, random));

            AsymmetricCipherKeyPair kpEnc = keyGen.GenerateKeyPair();

            PgpKeyPair ecdhKeyPair = new PgpKeyPair(PublicKeyAlgorithmTag.ECDH, kpEnc, DateTime.UtcNow);

            //
            // Generate a key ring
            //
            char[] passPhrase = "test".ToCharArray();
            PgpKeyRingGenerator keyRingGen = new PgpKeyRingGenerator(PgpSignature.PositiveCertification, ecdsaKeyPair,
                "*****@*****.**", SymmetricKeyAlgorithmTag.Aes256, passPhrase, true, null, null, random);
            keyRingGen.AddSubKey(ecdhKeyPair);

            PgpPublicKeyRing pubRing = keyRingGen.GeneratePublicKeyRing();

            // TODO: add check of KdfParameters
            DoBasicKeyRingCheck(pubRing);

            PgpSecretKeyRing secRing = keyRingGen.GenerateSecretKeyRing();

            PgpPublicKeyRing pubRingEnc = new PgpPublicKeyRing(pubRing.GetEncoded());
            if (!Arrays.AreEqual(pubRing.GetEncoded(), pubRingEnc.GetEncoded()))
            {
                Fail("public key ring encoding failed");
            }

            PgpSecretKeyRing secRingEnc = new PgpSecretKeyRing(secRing.GetEncoded());
            if (!Arrays.AreEqual(secRing.GetEncoded(), secRingEnc.GetEncoded()))
            {
                Fail("secret key ring encoding failed");
            }

            PgpPrivateKey pgpPrivKey = secRing.GetSecretKey().ExtractPrivateKey(passPhrase);
        }
예제 #47
0
        private void GenerateAndSign()
        {
            SecureRandom random = SecureRandom.GetInstance("SHA1PRNG");

            IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator("ECDSA");
            keyGen.Init(new ECKeyGenerationParameters(SecObjectIdentifiers.SecP256r1, random));

            AsymmetricCipherKeyPair kpSign = keyGen.GenerateKeyPair();

            PgpKeyPair ecdsaKeyPair = new PgpKeyPair(PublicKeyAlgorithmTag.ECDsa, kpSign, DateTime.UtcNow);

            byte[] msg = Encoding.ASCII.GetBytes("hello world!");

            //
            // try a signature
            //
            PgpSignatureGenerator signGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.ECDsa, HashAlgorithmTag.Sha256);
            signGen.InitSign(PgpSignature.BinaryDocument, ecdsaKeyPair.PrivateKey);

            signGen.Update(msg);

            PgpSignature sig = signGen.Generate();

            sig.InitVerify(ecdsaKeyPair.PublicKey);
            sig.Update(msg);

            if (!sig.Verify())
            {
                Fail("signature failed to verify!");
            }

            //
            // generate a key ring
            //
            char[] passPhrase = "test".ToCharArray();
            PgpKeyRingGenerator keyRingGen = new PgpKeyRingGenerator(PgpSignature.PositiveCertification, ecdsaKeyPair,
                "*****@*****.**", SymmetricKeyAlgorithmTag.Aes256, passPhrase, true, null, null, random);

            PgpPublicKeyRing pubRing = keyRingGen.GeneratePublicKeyRing();
            PgpSecretKeyRing secRing = keyRingGen.GenerateSecretKeyRing();

            PgpPublicKeyRing pubRingEnc = new PgpPublicKeyRing(pubRing.GetEncoded());
            if (!Arrays.AreEqual(pubRing.GetEncoded(), pubRingEnc.GetEncoded()))
            {
                Fail("public key ring encoding failed");
            }

            PgpSecretKeyRing secRingEnc = new PgpSecretKeyRing(secRing.GetEncoded());
            if (!Arrays.AreEqual(secRing.GetEncoded(), secRingEnc.GetEncoded()))
            {
                Fail("secret key ring encoding failed");
            }


            //
            // try a signature using encoded key
            //
            signGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.ECDsa, HashAlgorithmTag.Sha256);
            signGen.InitSign(PgpSignature.BinaryDocument, secRing.GetSecretKey().ExtractPrivateKey(passPhrase));
            signGen.Update(msg);

            sig = signGen.Generate();
            sig.InitVerify(secRing.GetSecretKey().PublicKey);
            sig.Update(msg);

            if (!sig.Verify())
            {
                Fail("re-encoded signature failed to verify!");
            }
        }
예제 #48
0
        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");
            }
        }
예제 #49
0
        public void PerformTest1()
        {
            PgpPublicKeyRingBundle pubRings = new PgpPublicKeyRingBundle(pub1);

            int count = 0;

            foreach (PgpPublicKeyRing pgpPub1 in pubRings.GetKeyRings())
            {
                count++;

                int keyCount = 0;
                byte[] bytes = pgpPub1.GetEncoded();

                PgpPublicKeyRing pgpPub2 = new PgpPublicKeyRing(bytes);

                foreach (PgpPublicKey pubKey in pgpPub2.GetPublicKeys())
                {
                    keyCount++;

                    foreach (PgpSignature sig in pubKey.GetSignatures())
                    {
                        if (sig == null)
                            Fail("null signature found");
                    }
                }

                if (keyCount != 2)
                {
                    Fail("wrong number of public keys");
                }
            }

            if (count != 1)
            {
                Fail("wrong number of public keyrings");
            }

            //
            // exact match
            //
            count = 0;
            foreach (PgpPublicKeyRing pgpPub3 in pubRings.GetKeyRings("test (Test key) <*****@*****.**>"))
            {
                if (pgpPub3 == null)
                    Fail("null keyring found");

                count++;
            }

            if (count != 1)
            {
                Fail("wrong number of public keyrings on exact match");
            }

            //
            // partial match 1 expected
            //
            count = 0;
            foreach (PgpPublicKeyRing pgpPub4 in pubRings.GetKeyRings("test", true))
            {
                if (pgpPub4 == null)
                    Fail("null keyring found");

                count++;
            }

            if (count != 1)
            {
                Fail("wrong number of public keyrings on partial match 1");
            }

            //
            // partial match 0 expected
            //
            count = 0;
            foreach (PgpPublicKeyRing pgpPub5 in pubRings.GetKeyRings("XXX", true))
            {
                if (pgpPub5 == null)
                    Fail("null keyring found");

                count++;
            }

            if (count != 0)
            {
                Fail("wrong number of public keyrings on partial match 0");
            }

            //
            // case-insensitive partial match
            //
            count = 0;
            foreach (PgpPublicKeyRing pgpPub6 in pubRings.GetKeyRings("*****@*****.**", true, true))
            {
                if (pgpPub6 == null)
                    Fail("null keyring found");

                count++;
            }

            if (count != 1)
            {
                Fail("wrong number of public keyrings on case-insensitive partial match");
            }

            PgpSecretKeyRingBundle secretRings = new PgpSecretKeyRingBundle(sec1);
            count = 0;

            foreach (PgpSecretKeyRing pgpSec1 in secretRings.GetKeyRings())
            {
                count++;

                int keyCount = 0;

                byte[] bytes = pgpSec1.GetEncoded();

                PgpSecretKeyRing pgpSec2 = new PgpSecretKeyRing(bytes);

                foreach (PgpSecretKey k in pgpSec2.GetSecretKeys())
                {
                    keyCount++;
                    PgpPublicKey pk = k.PublicKey;

                    pk.GetSignatures();

                    byte[] pkBytes = pk.GetEncoded();

                    PgpPublicKeyRing pkR = new PgpPublicKeyRing(pkBytes);
                }

                if (keyCount != 2)
                {
                    Fail("wrong number of secret keys");
                }
            }

            if (count != 1)
            {
                Fail("wrong number of secret keyrings");
            }

            //
            // exact match
            //
            count = 0;
            foreach (PgpSecretKeyRing o1 in secretRings.GetKeyRings("test (Test key) <*****@*****.**>"))
            {
                if (o1 == null)
                    Fail("null keyring found");

                count++;
            }

            if (count != 1)
            {
                Fail("wrong number of secret keyrings on exact match");
            }

            //
            // partial match 1 expected
            //
            count = 0;
            foreach (PgpSecretKeyRing o2 in secretRings.GetKeyRings("test", true))
            {
                if (o2 == null)
                    Fail("null keyring found");

                count++;
            }

            if (count != 1)
            {
                Fail("wrong number of secret keyrings on partial match 1");
            }

            //
            // exact match 0 expected
            //
            count = 0;
            foreach (PgpSecretKeyRing o3 in secretRings.GetKeyRings("test", false))
            {
                if (o3 == null)
                    Fail("null keyring found");

                count++;
            }

            if (count != 0)
            {
                Fail("wrong number of secret keyrings on partial match 0");
            }

            //
            // case-insensitive partial match
            //
            count = 0;
            foreach (PgpSecretKeyRing o4 in secretRings.GetKeyRings("*****@*****.**", true, true))
            {
                if (o4 == null)
                    Fail("null keyring found");

                count++;
            }

            if (count != 1)
            {
                Fail("wrong number of secret keyrings on case-insensitive partial match");
            }
        }
예제 #50
0
        private void DoTestEncMessage()
        {
            PgpObjectFactory pgpFact = new PgpObjectFactory(encMessage);

            PgpEncryptedDataList encList = (PgpEncryptedDataList)pgpFact.NextPgpObject();

            PgpPublicKeyEncryptedData encP = (PgpPublicKeyEncryptedData)encList[0];

            PgpPublicKey publicKey = new PgpPublicKeyRing(testPubKey).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());

            PgpLiteralData lData = (PgpLiteralData)compFact.NextPgpObject();

            if (!"test.txt".Equals(lData.FileName))
            {
                Fail("wrong file name detected");
            }
        }
예제 #51
0
        public void PerformTest10()
        {
            PgpSecretKeyRing secretRing = new PgpSecretKeyRing(sec10);

            foreach (PgpSecretKey secretKey in secretRing.GetSecretKeys())
            {
                PgpPublicKey pubKey = secretKey.PublicKey;

                if (pubKey.ValidDays != 28)
                {
                    Fail("days wrong on secret key ring");
                }

                if (pubKey.GetValidSeconds() != 28 * 24 * 60 * 60)
                {
                    Fail("seconds wrong on secret key ring");
                }
            }

            PgpPublicKeyRing publicRing = new PgpPublicKeyRing(pub10);

            foreach (PgpPublicKey pubKey in publicRing.GetPublicKeys())
            {
                if (pubKey.ValidDays != 28)
                {
                    Fail("days wrong on public key ring");
                }

                if (pubKey.GetValidSeconds() != 28 * 24 * 60 * 60)
                {
                    Fail("seconds wrong on public key ring");
                }
            }
        }
        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");
            }
        }
예제 #53
0
        public void PerformTest11()
        {
            PgpPublicKeyRing pubRing = new PgpPublicKeyRing(subKeyBindingKey);

            foreach (PgpPublicKey key in pubRing.GetPublicKeys())
            {
                if (key.GetValidSeconds() != 0)
                {
                    Fail("expiration time non-zero");
                }
            }
        }
        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");
            }
        }
예제 #55
0
        public void PerformTest2()
        {
            PgpPublicKeyRingBundle pubRings = new PgpPublicKeyRingBundle(pub2);

            int count = 0;

            byte[] encRing = pubRings.GetEncoded();

            pubRings = new PgpPublicKeyRingBundle(encRing);

            foreach (PgpPublicKeyRing pgpPub1 in pubRings.GetKeyRings())
            {
                count++;

                int keyCount = 0;

                byte[] bytes = pgpPub1.GetEncoded();

                PgpPublicKeyRing pgpPub2 = new PgpPublicKeyRing(bytes);

                foreach (PgpPublicKey pk in pgpPub2.GetPublicKeys())
                {
                    byte[] pkBytes = pk.GetEncoded();

                    PgpPublicKeyRing pkR = new PgpPublicKeyRing(pkBytes);

                    keyCount++;
                }

                if (keyCount != 2)
                {
                    Fail("wrong number of public keys");
                }
            }

            if (count != 2)
            {
                Fail("wrong number of public keyrings");
            }

            PgpSecretKeyRingBundle secretRings2 = new PgpSecretKeyRingBundle(sec2);

            count = 0;

            encRing = secretRings2.GetEncoded();
            PgpSecretKeyRingBundle secretRings = new PgpSecretKeyRingBundle(encRing);

            foreach (PgpSecretKeyRing pgpSec1 in secretRings2.GetKeyRings())
            {
                count++;

                int keyCount = 0;

                byte[] bytes = pgpSec1.GetEncoded();

                PgpSecretKeyRing pgpSec2 = new PgpSecretKeyRing(bytes);

                foreach (PgpSecretKey k in pgpSec2.GetSecretKeys())
                {
                    keyCount++;
                    PgpPublicKey pk = k.PublicKey;

                    if (pk.KeyId == -1413891222336124627L)
                    {
                        int sCount = 0;

                        foreach (PgpSignature pgpSignature in pk.GetSignaturesOfType(PgpSignature.SubkeyBinding))
                        {
                            int type = pgpSignature.SignatureType;
                            if (type != PgpSignature.SubkeyBinding)
                            {
                                Fail("failed to return correct signature type");
                            }
                            sCount++;
                        }

                        if (sCount != 1)
                        {
                            Fail("failed to find binding signature");
                        }
                    }

                    pk.GetSignatures();

                    if (k.KeyId == -4049084404703773049L
                        || k.KeyId == -1413891222336124627L)
                    {
                        k.ExtractPrivateKey(sec2pass1);
                    }
                    else if (k.KeyId == -6498553574938125416L
                        || k.KeyId == 59034765524361024L)
                    {
                        k.ExtractPrivateKey(sec2pass2);
                    }
                }

                if (keyCount != 2)
                {
                    Fail("wrong number of secret keys");
                }
            }

            if (count != 2)
            {
                Fail("wrong number of secret keyrings");
            }
        }
예제 #56
0
        public void PerformTest3()
        {
            PgpPublicKeyRingBundle pubRings = new PgpPublicKeyRingBundle(pub3);

            int count = 0;

            byte[] encRing = pubRings.GetEncoded();

            pubRings = new PgpPublicKeyRingBundle(encRing);

            foreach (PgpPublicKeyRing pgpPub1 in pubRings.GetKeyRings())
            {
                count++;

                int keyCount = 0;

                byte[] bytes = pgpPub1.GetEncoded();

                PgpPublicKeyRing pgpPub2 = new PgpPublicKeyRing(bytes);

                foreach (PgpPublicKey pubK in pgpPub2.GetPublicKeys())
                {
                    keyCount++;
                    pubK.GetSignatures();
                }

                if (keyCount != 2)
                {
                    Fail("wrong number of public keys");
                }
            }

            if (count != 1)
            {
                Fail("wrong number of public keyrings");
            }

            PgpSecretKeyRingBundle secretRings2 = new PgpSecretKeyRingBundle(sec3);

            count = 0;

            encRing = secretRings2.GetEncoded();

            PgpSecretKeyRingBundle secretRings = new PgpSecretKeyRingBundle(encRing);

            foreach (PgpSecretKeyRing pgpSec1 in secretRings2.GetKeyRings())
            {
                count++;

                int keyCount = 0;

                byte[] bytes = pgpSec1.GetEncoded();

                PgpSecretKeyRing pgpSec2 = new PgpSecretKeyRing(bytes);

                foreach (PgpSecretKey k in pgpSec2.GetSecretKeys())
                {
                    keyCount++;
                    k.ExtractPrivateKey(sec3pass1);
                }

                if (keyCount != 2)
                {
                    Fail("wrong number of secret keys");
                }
            }

            if (count != 1)
            {
                Fail("wrong number of secret keyrings");
            }
        }
예제 #57
0
        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");
            }
        }