예제 #1
0
        private static PgpPrivateKey FindSecretKey(PgpSecretKeyRingBundle pgpSec, long keyId, char[] pass)
        {
            PgpSecretKey pgpSecKey = pgpSec.GetSecretKey(keyId);

            if (pgpSecKey == null)
            {
                return(null);
            }

            return(pgpSecKey.ExtractPrivateKey(pass));
        }
        /// <summary>
        /// Sign a file with PGP signature. See documentation at https://github.com/CommunityHiQ/Frends.Community.PgpSignature Returns: Object {string FilePath}
        /// </summary>
        public static Result PGPSignFile(Input input)
        {
            HashAlgorithmTag digest = input.HashFunction.ConvertEnum <HashAlgorithmTag>();

            using (var privateKeyStream = File.OpenRead(input.PrivateKeyFile))
            {
                PgpSecretKey                   pgpSecKey                   = ReadSecretKey(privateKeyStream);
                PgpPrivateKey                  pgpPrivKey                  = pgpSecKey.ExtractPrivateKey(input.Password.ToCharArray());
                PgpSignatureGenerator          signatureGenerator          = new PgpSignatureGenerator(pgpSecKey.PublicKey.Algorithm, digest);
                PgpSignatureSubpacketGenerator signatureSubpacketGenerator = new PgpSignatureSubpacketGenerator();

                signatureGenerator.InitSign(Org.BouncyCastle.Bcpg.OpenPgp.PgpSignature.BinaryDocument, pgpPrivKey);

                IEnumerator enumerator = pgpSecKey.PublicKey.GetUserIds().GetEnumerator();
                if (enumerator.MoveNext())
                {
                    signatureSubpacketGenerator.SetSignerUserId(false, (string)enumerator.Current);
                    signatureGenerator.SetHashedSubpackets(signatureSubpacketGenerator.Generate());
                }

                using (var outputStream = File.Create(input.OutputFile))
                {
                    ArmoredOutputStream armoredOutputStream = new ArmoredOutputStream(outputStream);
                    BcpgOutputStream    bcbgOutputStream    = new BcpgOutputStream(armoredOutputStream);
                    signatureGenerator.GenerateOnePassVersion(false).Encode(bcbgOutputStream);

                    FileInfo file = new FileInfo(input.InputFile);
                    PgpLiteralDataGenerator literalDataGenerator = new PgpLiteralDataGenerator();
                    Stream literalDataOut = literalDataGenerator.Open(bcbgOutputStream, PgpLiteralData.Binary, file);
                    using (var fileIn = file.OpenRead())
                    {
                        int ch;

                        while ((ch = fileIn.ReadByte()) >= 0)
                        {
                            literalDataOut.WriteByte((byte)ch);
                            signatureGenerator.Update((byte)ch);
                        }

                        fileIn.Close();
                        literalDataGenerator.Close();
                        signatureGenerator.Generate().Encode(bcbgOutputStream);
                        armoredOutputStream.Close();
                        outputStream.Close();

                        Result ret = new Result
                        {
                            FilePath = input.OutputFile
                        };
                        return(ret);
                    }
                }
            }
        }
예제 #3
0
 private static PgpPrivateKey GetPrivateKey(PgpSecretKey secretKey, string?passphrase)
 {
     try
     {
         return(secretKey.ExtractPrivateKey(passphrase?.ToCharArray()));
     }
     catch (PgpException)
     {
         throw new WrongPassphraseException();
     }
 }
예제 #4
0
        /// <summary>
        /// Search a secret key ring collection for a secret key corresponding to keyID if it exists.
        /// </summary>
        /// <param name="secretKeyRingBundle"></param>
        /// <param name="keyID"></param>
        /// <param name="passPhrase"></param>
        /// <returns></returns>
        /// <exception cref="PgpException"></exception>
        internal static PgpPrivateKey FindSecretKey(PgpSecretKeyRingBundle secretKeyRingBundle, long keyId, char[] passPhrase)
        {
            PgpSecretKey _pgpSecretKey = secretKeyRingBundle.GetSecretKey(keyId);

            if (_pgpSecretKey == null)
            {
                return(null);
            }

            return(_pgpSecretKey.ExtractPrivateKey(passPhrase));
        }
        private PgpPrivateKey FindKeyById(PgpSecretKeyRingBundle privRings, long keyId)
        {
            PgpSecretKey pgpSecKey = privRings.GetSecretKey(keyId);

            if (pgpSecKey == null)
            {
                return(null);
            }

            return(pgpSecKey.ExtractPrivateKey(null));
        }
예제 #6
0
        public PgpPrivateKey FindSecretKey(long keyId)
        {
            PgpSecretKey pgpSecKey = SecretKeys.GetSecretKey(keyId);

            if (pgpSecKey == null)
            {
                return(null);
            }

            return(pgpSecKey.ExtractPrivateKey(_passPhrase.ToCharArray()));
        }
예제 #7
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!");
            }
        }
예제 #8
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");
            }
        }
    private PgpPrivateKey GetPrivateKey(string password, string private_key_path)
    {
        PgpSecretKey secret_key = GetSecretKey(private_key_path);

        PgpPrivateKey private_key = secret_key.ExtractPrivateKey(password.ToCharArray());

        if (private_key == null)
        {
            return(null);
        }

        return(private_key);
    }
예제 #10
0
        public void Setup()
        {
            // Read the public key
            var pgpPub = new PgpPublicKeyRing(testPubKey);

            pubKey = pgpPub.GetPublicKey();

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

            secretKey  = sKey.GetSecretKey();
            pgpPrivKey = secretKey.ExtractPrivateKey(pass);
        }
        public static PgpPrivateKey ReadPrivateKey(
            string keyIn,
            string passPhrase)
        {
            PgpSecretKey  secretKey  = ReadSecretKey(keyIn);
            PgpPrivateKey privateKey = secretKey.ExtractPrivateKey(passPhrase.ToCharArray());

            if (privateKey != null)
            {
                return(privateKey);
            }

            throw new ArgumentException("No private key found in secret key.");
        }
예제 #12
0
 public static void UnlockKey(string password)
 {
     try {
         var dec = masterSecretKey.ExtractPrivateKey(password.ToCharArray());
         if (!TestPrivateKey(masterSecretKey.PublicKey, dec))
         {
             throw new Exception("Invalid password for master key!");
         }
         masterPrivateKey = dec;
         Logger.Log(GpgToolsLog, "Master Key Unlocked");
     } catch (Exception) {
         throw new Exception("Invalid password for master key!");
     }
 }
        private static PgpPrivateKey FindSecretKey(Stream keyIn, long keyId, char[] pass)
        {
            PgpSecretKeyRingBundle pgpSec = new PgpSecretKeyRingBundle(
                PgpUtilities.GetDecoderStream(keyIn));

            PgpSecretKey pgpSecKey = pgpSec.GetSecretKey(keyId);

            if (pgpSecKey == null)
            {
                return(null);
            }

            return(pgpSecKey.ExtractPrivateKey(pass));
        }
예제 #14
0
        // http://stackoverflow.com/questions/20572737/sign-and-verify-xml-file-in-c-sharp



        public void SignFile(string hashAlgorithm, string fileName, System.IO.Stream privateKeyStream
                             , string privateKeyPassword, System.IO.Stream outStream)
        {
            PgpSecretKey  pgpSec     = ReadSigningSecretKey(privateKeyStream);
            PgpPrivateKey pgpPrivKey = null;

            pgpPrivKey = pgpSec.ExtractPrivateKey(privateKeyPassword.ToCharArray());



            PgpSignatureGenerator sGen = new PgpSignatureGenerator(pgpSec.PublicKey.Algorithm, ParseHashAlgorithm(hashAlgorithm));

            sGen.InitSign(PgpSignature.BinaryDocument, pgpPrivKey);

            foreach (string userId in pgpSec.PublicKey.GetUserIds())
            {
                PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator();

                spGen.SetSignerUserId(false, userId);
                sGen.SetHashedSubpackets(spGen.Generate());
            }

            CompressionAlgorithmTag    compression = PreferredCompression(pgpSec.PublicKey);
            PgpCompressedDataGenerator cGen        = new PgpCompressedDataGenerator(compression);

            BcpgOutputStream bOut = new BcpgOutputStream(cGen.Open(outStream));

            sGen.GenerateOnePassVersion(false).Encode(bOut);

            System.IO.FileInfo      file = new System.IO.FileInfo(fileName);
            System.IO.FileStream    fIn  = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
            PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator();

            System.IO.Stream lOut = lGen.Open(bOut, PgpLiteralData.Binary, file);

            int ch = 0;

            while ((ch = fIn.ReadByte()) >= 0)
            {
                lOut.WriteByte((byte)ch);
                sGen.Update((byte)ch);
            }

            fIn.Close();
            sGen.Generate().Encode(bOut);
            lGen.Close();
            cGen.Close();
            outStream.Close();
        }
예제 #15
0
        private static byte[] SignPublicKey(
            PgpSecretKey secretKey,
            string secretKeyPass,
            PgpPublicKey keyToBeSigned,
            string notationName,
            string notationValue,
            bool armor)
        {
            Stream os = new MemoryStream();

            if (armor)
            {
                os = new ArmoredOutputStream(os);
            }

            PgpPrivateKey pgpPrivKey = secretKey.ExtractPrivateKey(
                secretKeyPass.ToCharArray());

            PgpSignatureGenerator sGen = new PgpSignatureGenerator(
                secretKey.PublicKey.Algorithm, HashAlgorithmTag.Sha1);

            sGen.InitSign(PgpSignature.DirectKey, pgpPrivKey);

            BcpgOutputStream bOut = new BcpgOutputStream(os);

            sGen.GenerateOnePassVersion(false).Encode(bOut);

            PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator();

            bool isHumanReadable = true;

            spGen.SetNotationData(true, isHumanReadable, notationName, notationValue);

            PgpSignatureSubpacketVector packetVector = spGen.Generate();

            sGen.SetHashedSubpackets(packetVector);

            bOut.Flush();

            if (armor)
            {
                os.Close();
            }

            return(PgpPublicKey.AddCertification(keyToBeSigned, sGen.Generate()).GetEncoded());
        }
예제 #16
0
        public void GenerateTest(string type, string message)
        {
            PgpSecretKey  pgpSecKey  = ReadSecretKey(new MemoryStream(secretKey));
            PgpPrivateKey pgpPrivKey = pgpSecKey.ExtractPrivateKey("");
            MemoryStream  bOut       = new MemoryStream();

            using (var messageGenerator = new PgpMessageGenerator(new ArmoredPacketWriter(bOut)))
                using (var signedGenerator = messageGenerator.CreateSigned(PgpSignatureType.CanonicalTextDocument, pgpPrivKey, PgpHashAlgorithm.Sha256))
                {
                    signedGenerator.HashedAttributes.SetSignerUserId(false, pgpSecKey.GetUserIds().First().UserId);
                    using (var literalStream = signedGenerator.CreateLiteral(PgpDataFormat.Text, "", DateTime.MinValue))
                    {
                        literalStream.Write(Encoding.UTF8.GetBytes(message));
                    }
                }
            byte[] bs = bOut.ToArray();
            MessageTest(type, Encoding.ASCII.GetString(bs, 0, bs.Length));
        }
        private PgpSignatureGenerator createSignatureGenerator()
        {
            PgpPrivateKey         privateKey         = secretKey.ExtractPrivateKey(password);
            PgpPublicKey          internalPublicKey  = secretKey.PublicKey;
            PgpSignatureGenerator signatureGenerator = new PgpSignatureGenerator(internalPublicKey.Algorithm, HashAlgorithmTag.Sha1);

            signatureGenerator.InitSign(PgpSignature.BinaryDocument, privateKey);
            var userIds = internalPublicKey.GetUserIds();

            foreach (var userId in userIds)
            {
                PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator();
                spGen.SetSignerUserId(false, (String)userId);
                signatureGenerator.SetHashedSubpackets(spGen.Generate());
                break;
            }
            return(signatureGenerator);
        }
예제 #18
0
        private string Decrypt(Stream input, PgpSecretKey secretKey, string passPhrase)
        {
            input = PgpUtilities.GetDecoderStream(input);

            PgpObjectFactory     pgpObjF = new PgpObjectFactory(input);
            PgpEncryptedDataList enc;
            PgpObject            obj = pgpObjF.NextPgpObject();

            if (obj is PgpEncryptedDataList)
            {
                enc = (PgpEncryptedDataList)obj;
            }
            else
            {
                enc = (PgpEncryptedDataList)pgpObjF.NextPgpObject();
            }

            PgpPublicKeyEncryptedData pbe = enc.GetEncryptedDataObjects().Cast <PgpPublicKeyEncryptedData>().First();
            Stream        clear;
            PgpPrivateKey privateKey = secretKey.ExtractPrivateKey(passPhrase.ToCharArray());

            clear = pbe.GetDataStream(privateKey);
            PgpObjectFactory plainFact = new PgpObjectFactory(clear);
            PgpObject        message   = plainFact.NextPgpObject();

            if (message is PgpCompressedData)
            {
                PgpCompressedData cData      = (PgpCompressedData)message;
                Stream            compDataIn = cData.GetDataStream();
                PgpObjectFactory  o          = new PgpObjectFactory(compDataIn);
                message = o.NextPgpObject();
                if (message is PgpOnePassSignatureList)
                {
                    message = o.NextPgpObject();
                }

                var ld     = (PgpLiteralData)message;
                var unc    = ld.GetInputStream();
                var reader = new StreamReader(unc);
                return(reader.ReadToEnd());
            }

            throw new NotImplementedException();
        }
예제 #19
0
        public void Generate25519()
        {
            // Generate a master key
            var ecdsa = new Ed25519();
            // Generate an encryption key
            var ecdh = new X25519();

            // 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");

            // Extract back the ECDH key and verify the encoded values to ensure correct endianness
            PgpSecretKey  pgpSecretKey = secRing.GetSecretKey(pubRing.GetPublicKey().KeyId);
            PgpPrivateKey pgpPrivKey   = pgpSecretKey.ExtractPrivateKey(passPhrase);

            /*if (!Arrays.AreEqual(((X25519PrivateKeyParameters)kpEnc.Private).GetEncoded(), ((X25519PrivateKeyParameters)pgpPrivKey.Key).GetEncoded()))
             * {
             *  Fail("private key round trip failed");
             * }
             * if (!Arrays.AreEqual(((X25519PublicKeyParameters)kpEnc.Public).GetEncoded(), ((X25519PublicKeyParameters)pgpSecretKey.PublicKey.GetKey()).GetEncoded()))
             * {
             *  Fail("private key round trip failed");
             * }*/
        }
예제 #20
0
        private static void CreateSignature(
            string fileName,
            Stream keyIn,
            Stream outputStream,
            char[]  pass,
            bool armor)
        {
            if (armor)
            {
                outputStream = new ArmoredOutputStream(outputStream);
            }

            PgpSecretKey          pgpSec     = PgpExampleUtilities.ReadSecretKey(keyIn);
            PgpPrivateKey         pgpPrivKey = pgpSec.ExtractPrivateKey(pass);
            PgpSignatureGenerator sGen       = new PgpSignatureGenerator(
                pgpSec.PublicKey.Algorithm, HashAlgorithmTag.Sha1);

            sGen.InitSign(PgpSignature.BinaryDocument, pgpPrivKey);

            BcpgOutputStream bOut = new BcpgOutputStream(outputStream);

            Stream fIn = File.OpenRead(fileName);

            int ch;

            while ((ch = fIn.ReadByte()) >= 0)
            {
                sGen.Update((byte)ch);
            }

            fIn.Close();

            sGen.Generate().Encode(bOut);

            if (armor)
            {
                outputStream.Close();
            }
        }
예제 #21
0
        static void Main(string[] args)
        {
            log2File("v1.0.0.0");
            // -e|-d
            // path_to_public_key
            // path_to_private_key@password|null@null
            // path_to_input_file
            // path_to_output_file
            //
            if (args.Length != 5)
            {
                displayHelp();
                return;
            }
            bool   isEncrypt   = args[0] == "-e";
            string pathPublic  = args[1];
            string pathPrivate = args[2].Split('@')[0];
            string password    = args[2].Split('@')[1];
            string pathInput   = args[3];
            string pathOutput  = args[4];

            PublicKey = GetPublicKey(pathPublic);
            SecretKey = (pathPrivate == "null") ? null : GetSecretKey(pathPrivate);
            if (SecretKey != null && !string.IsNullOrEmpty(password))
            {
                PrivateKey = SecretKey.ExtractPrivateKey(password.ToCharArray());
            }
            KeyAlgorithm = SymmetricKeyAlgorithmTag.TripleDes;

            if (isEncrypt)
            {
                Encrypt(pathInput, pathOutput);
            }
            else
            {
                Decrypt(pathInput, pathOutput);
            }
        }
예제 #22
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!");
            }
        }
        /// <summary>
        /// Sign public key with secret key. To access the private key from the
        /// secret container a password needs to be provided.
        /// </summary>
        /// <param name="secretKey">
        /// The secret key containing the private key for signing the public
        /// key.
        /// </param>
        /// <param name="password">
        /// The password of the secret key.
        /// </param>
        /// <param name="keyToBeSigned">
        /// The public key to be signed.
        /// </param>
        /// <param name="certain">
        /// Flag indicating whether or not the certification is positive or just
        /// casual.
        /// </param>
        /// <returns>
        /// Returns the <see cref="PgpPublicKey"/> adorned with a signature by the
        /// private key passed in.
        /// </returns>
        public static PgpPublicKey SignPublicKey(
            PgpSecretKey secretKey,
            string password,
            PgpPublicKey keyToBeSigned,
            bool certain)
        {
            var id = keyToBeSigned.GetUserIds().Cast <string>().FirstOrDefault();

            // Extracting private key, and getting ready to create a signature.
            var privateKey         = secretKey.ExtractPrivateKey(password.ToCharArray());
            var signatureGenerator = new PgpSignatureGenerator(secretKey.PublicKey.Algorithm, HashAlgorithmTag.Sha256);

            signatureGenerator.InitSign(
                certain ? PgpSignature.PositiveCertification : PgpSignature.CasualCertification,
                privateKey);

            // Creating a stream to wrap the results of operation.
            var outputStream       = new MemoryStream();
            var packetOutputStream = new BcpgOutputStream(outputStream);

            signatureGenerator.GenerateOnePassVersion(false).Encode(packetOutputStream);

            // Creating a generator.
            var subpacketSignatureGenerator = new PgpSignatureSubpacketGenerator();

            subpacketSignatureGenerator.SetSignerUserId(false, id);
            var packetVector = subpacketSignatureGenerator.Generate();

            signatureGenerator.SetHashedSubpackets(packetVector);
            packetOutputStream.Flush();

            // Returning the signed public key.
            return(PgpPublicKey.AddCertification(
                       keyToBeSigned,
                       id,
                       signatureGenerator.GenerateCertification(id, keyToBeSigned)));
        }
        private static string CreateSignature(
            string message,
            Stream keyIn,
            Stream outputStream,
            char[]  pass,
            bool armor)
        {
            if (armor)
            {
                outputStream = new ArmoredOutputStream(outputStream);
            }

            PgpSecretKey          pgpSec     = PgpExampleUtilities.ReadSecretKey(keyIn);
            PgpPrivateKey         pgpPrivKey = pgpSec.ExtractPrivateKey(pass);
            PgpSignatureGenerator sGen       = new PgpSignatureGenerator(
                pgpSec.PublicKey.Algorithm, HashAlgorithmTag.Sha1);

            sGen.InitSign(PgpSignature.BinaryDocument, pgpPrivKey);

            BcpgOutputStream bOut = new BcpgOutputStream(outputStream);

            sGen.Update(System.Text.Encoding.UTF8.GetBytes(message));
            PgpSignature sig = sGen.Generate();

            sig.Encode(bOut);

            if (armor)
            {
                outputStream.Close();
            }

            MemoryStream ms = new MemoryStream();

            sig.Encode(ms);
            byte[] bytes = ms.ToArray();
            return(Convert.ToBase64String(bytes));
        }
예제 #25
0
        private void DoTestKey(long keyId, string passphrase)
        {
            PgpSecretKeyRingBundle secretKeyRing = LoadSecretKeyCollection("secring.gpg");

            PgpSecretKeyRing secretKey = secretKeyRing.GetSecretKeyRing(keyId);

            Assert.NotNull(secretKey, "Could not locate secret keyring with Id=" + keyId);

            PgpSecretKey key = secretKey.GetSecretKey();

            Assert.NotNull(key, "Could not locate secret key!");

            try
            {
                PgpPrivateKey privateKey = key.ExtractPrivateKey(passphrase);
                Assert.IsTrue(privateKey.KeyId == keyId);
            }
            catch (PgpException e)
            {
                throw new PgpException("Password incorrect!", e);
            }

            // all fine!
        }
예제 #26
0
        public void PerformTest()
        {
            //
            // Read the public key
            //
            PgpPublicKeyRing pgpPub = new PgpPublicKeyRing(testPubKey);

            var firstUserId = pgpPub.GetPublicKey().GetUserIds().FirstOrDefault();

            Assert.NotNull(firstUserId);
            Assert.AreEqual(1, firstUserId.SelfCertifications.Count);
            Assert.IsTrue(firstUserId.SelfCertifications[0].Verify());

            //
            // write a public key
            //
            MemoryStream bOut = new MemoryStream();

            pgpPub.Encode(bOut);
            Assert.AreEqual(testPubKey, bOut.ToArray());

            //
            // Read the public key
            //
            PgpPublicKeyRing pgpPubV3 = new PgpPublicKeyRing(testPubKeyV3);

            //
            // write a V3 public key
            //
            bOut = new MemoryStream();

            pgpPubV3.Encode(bOut);

            //
            // Read a v3 private key
            //
            var passP = "FIXCITY_QA";

            {
                PgpSecretKeyRing pgpPriv2         = new PgpSecretKeyRing(testPrivKeyV3);
                PgpSecretKey     pgpPrivSecretKey = pgpPriv2.GetSecretKey();
                PgpPrivateKey    pgpPrivKey2      = pgpPrivSecretKey.ExtractPrivateKey(passP);

                //
                // write a v3 private key
                //
                bOut = new MemoryStream();
                pgpPriv2.Encode(bOut);
                byte[] result = bOut.ToArray();
                Assert.AreEqual(testPrivKeyV3, result);
            }

            //
            // Read the private key
            //
            PgpSecretKeyRing pgpPriv    = new PgpSecretKeyRing(testPrivKey);
            PgpPrivateKey    pgpPrivKey = pgpPriv.GetSecretKey().ExtractPrivateKey(pass);

            //
            // write a private key
            //
            bOut = new MemoryStream();
            pgpPriv.Encode(bOut);
            Assert.AreEqual(testPrivKey, bOut.ToArray());

            //
            // test encryption
            //

            /*var c = pubKey;
             *
             * //                c.Init(Cipher.ENCRYPT_MODE, pubKey);
             *
             * byte[] inBytes = Encoding.ASCII.GetBytes("hello world");
             * byte[] outBytes = c.DoFinal(inBytes);
             *
             * //                c.Init(Cipher.DECRYPT_MODE, pgpPrivKey.GetKey());
             * c.Init(false, pgpPrivKey.Key);
             *
             * outBytes = c.DoFinal(outBytes);
             *
             * if (!Arrays.AreEqual(inBytes, outBytes))
             * {
             *  Fail("decryption failed.");
             * }*/

            //
            // test signature message
            //
            var compressedMessage = (PgpCompressedMessage)PgpMessage.ReadMessage(sig1);
            var signedMessage     = (PgpSignedMessage)compressedMessage.ReadMessage();
            var literalMessage    = (PgpLiteralMessage)signedMessage.ReadMessage();

            literalMessage.GetStream().CopyTo(Stream.Null);
            Assert.True(signedMessage.Verify(pgpPub.GetPublicKey(signedMessage.KeyId)));

            //
            // encrypted message - read subkey
            //
            pgpPriv = new PgpSecretKeyRing(subKey);

            //
            // encrypted message
            //
            byte[] text             = Encoding.ASCII.GetBytes("hello world!\n");
            var    encryptedMessage = (PgpEncryptedMessage)PgpMessage.ReadMessage(enc1);

            var encKeyId = encryptedMessage.KeyIds.First();

            pgpPrivKey        = pgpPriv.GetSecretKey(encKeyId).ExtractPrivateKey(pass);
            compressedMessage = (PgpCompressedMessage)encryptedMessage.DecryptMessage(pgpPrivKey);
            literalMessage    = (PgpLiteralMessage)compressedMessage.ReadMessage();
            Assert.AreEqual("test.txt", literalMessage.FileName);
            byte[] bytes = Streams.ReadAll(literalMessage.GetStream());
            Assert.AreEqual(text, bytes);

            //
            // encrypt - short message
            //
            byte[] shortText = { (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o' };

            MemoryStream cbOut = new MemoryStream();

            var messageGenerator = new PgpMessageGenerator(cbOut);

            using (var encryptedGenerator = messageGenerator.CreateEncrypted(PgpSymmetricKeyAlgorithm.Cast5))
            {
                encryptedGenerator.AddMethod(pgpPriv.GetSecretKey(encKeyId));
                using (var literalStream = encryptedGenerator.CreateLiteral(PgpDataFormat.Binary, "", DateTime.UtcNow))
                {
                    literalStream.Write(shortText);
                }
            }

            cbOut.Position   = 0;
            encryptedMessage = (PgpEncryptedMessage)PgpMessage.ReadMessage(cbOut);
            pgpPrivKey       = pgpPriv.GetSecretKey(encryptedMessage.KeyIds.First()).ExtractPrivateKey(pass);
            //Assert.AreEqual(SymmetricKeyAlgorithmTag.Cast5, ((PgpPublicKeyEncryptedData)encryptedMessage.Methods[0]).GetSymmetricAlgorithm(pgpPrivKey));
            literalMessage = (PgpLiteralMessage)encryptedMessage.DecryptMessage(pgpPrivKey);
            Assert.AreEqual("", literalMessage.FileName);
            bytes = Streams.ReadAll(literalMessage.GetStream());
            Assert.AreEqual(shortText, bytes);

            //
            // encrypt
            //
            cbOut = new MemoryStream();

            messageGenerator = new PgpMessageGenerator(cbOut);
            using (var encryptedGenerator = messageGenerator.CreateEncrypted(PgpSymmetricKeyAlgorithm.Cast5))
            {
                encryptedGenerator.AddMethod(pgpPriv.GetSecretKey(encKeyId));
                using (var literalStream = encryptedGenerator.CreateLiteral(PgpDataFormat.Binary, "", DateTime.UtcNow))
                {
                    literalStream.Write(text);
                }
            }

            cbOut.Position   = 0;
            encryptedMessage = (PgpEncryptedMessage)PgpMessage.ReadMessage(cbOut);
            pgpPrivKey       = pgpPriv.GetSecretKey(encryptedMessage.KeyIds.First()).ExtractPrivateKey(pass);
            literalMessage   = (PgpLiteralMessage)encryptedMessage.DecryptMessage(pgpPrivKey);
            bytes            = Streams.ReadAll(literalMessage.GetStream());
            Assert.AreEqual(text, bytes);

            //
            // read public key with sub key.
            //

            /*pgpF = new PgpObjectFactory(subPubKey);
             * object o;
             * while ((o = pgpFact.NextPgpObject()) != null)
             * {
             *  // TODO Should something be tested here?
             *  // Console.WriteLine(o);
             * }*/

            //
            // key pair generation - CAST5 encryption
            //
            var passPhrase = "hello";
            var rsa        = RSA.Create(1024);

            var keyRingGenerator = new PgpKeyRingGenerator(rsa, "fred", passPhrase);

            var secretKey = keyRingGenerator.GenerateSecretKeyRing().GetSecretKey();

            PgpPublicKey key = new PgpPublicKey(secretKey);

            firstUserId = key.GetUserIds().FirstOrDefault();
            Assert.NotNull(firstUserId);
            Assert.AreEqual(1, firstUserId.SelfCertifications.Count);
            Assert.IsTrue(firstUserId.SelfCertifications[0].Verify());

            pgpPrivKey = secretKey.ExtractPrivateKey(passPhrase);

            key = PgpPublicKey.RemoveCertification(key, firstUserId, firstUserId.SelfCertifications[0]);
            Assert.NotNull(key);

            byte[] keyEnc = key.GetEncoded();

            key = PgpPublicKey.AddCertification(key, firstUserId.UserId, firstUserId.SelfCertifications[0]);

            keyEnc = key.GetEncoded();

            var revocation = PgpCertification.GenerateKeyRevocation(
                secretKey,
                secretKey.ExtractPrivateKey(passPhrase),
                key);

            key = PgpPublicKey.AddCertification(key, revocation);

            keyEnc = key.GetEncoded();

            PgpPublicKeyRing tmpRing = new PgpPublicKeyRing(keyEnc);

            key = tmpRing.GetPublicKey();

            revocation = key.KeyCertifications.Where(c => c.SignatureType == PgpSignatureType.KeyRevocation).FirstOrDefault();
            Assert.NotNull(revocation);
            Assert.IsTrue(revocation.Verify(key));

            //
            // use of PgpKeyPair
            //
            PgpKeyPair pgpKp = new PgpKeyPair(rsa, DateTime.UtcNow);

            PgpPublicKey  k1 = pgpKp.PublicKey;
            PgpPrivateKey k2 = pgpKp.PrivateKey;

            k1.GetEncoded();

            MixedTest(k2, k1);

            //
            // key pair generation - AES_256 encryption. -- XXX
            //
            //kp = kpg.GenerateKeyPair();
            rsa = RSA.Create(1024);

            keyRingGenerator = new PgpKeyRingGenerator(rsa, "fred", passPhrase /*, encAlgorithm: PgpSymmetricKeyAlgorithm.Aes256*/);

            secretKey = keyRingGenerator.GenerateSecretKeyRing().GetSecretKey();

            secretKey.ExtractPrivateKey(passPhrase);

            secretKey.Encode(new MemoryStream());

            //
            // secret key password changing.
            //
            const string newPass = "******";

            secretKey = PgpSecretKey.CopyWithNewPassword(secretKey, passPhrase, newPass);

            secretKey.ExtractPrivateKey(newPass);

            secretKey.Encode(new MemoryStream());

            key = new PgpPublicKey(secretKey);

            key.Encode(new MemoryStream());

            firstUserId = key.GetUserIds().FirstOrDefault();
            Assert.NotNull(firstUserId);
            Assert.AreEqual(1, firstUserId.SelfCertifications.Count);
            Assert.IsTrue(firstUserId.SelfCertifications[0].Verify());

            pgpPrivKey = secretKey.ExtractPrivateKey(newPass);

            //
            // signature generation
            //
            const string data = "hello world!";

            byte[]   dataBytes    = Encoding.ASCII.GetBytes(data);
            DateTime testDateTime = new DateTime(1973, 7, 27);

            bOut             = new MemoryStream();
            messageGenerator = new PgpMessageGenerator(bOut);
            using (var compressedGenerator = messageGenerator.CreateCompressed(PgpCompressionAlgorithm.Zip))
                using (var signingGenerator = compressedGenerator.CreateSigned(PgpSignatureType.BinaryDocument, pgpPrivKey, PgpHashAlgorithm.Sha1))
                    using (var literalStream = signingGenerator.CreateLiteral(PgpDataFormat.Binary, "_CONSOLE", testDateTime))
                    {
                        literalStream.Write(dataBytes);
                    }

            //
            // verify generated signature
            //
            bOut.Position     = 0;
            compressedMessage = (PgpCompressedMessage)PgpMessage.ReadMessage(bOut);
            signedMessage     = (PgpSignedMessage)compressedMessage.ReadMessage();
            literalMessage    = (PgpLiteralMessage)signedMessage.ReadMessage();
            Assert.AreEqual(testDateTime, literalMessage.ModificationTime);
            literalMessage.GetStream().CopyTo(Stream.Null);
            Assert.IsTrue(signedMessage.Verify(secretKey));

            //
            // signature generation - version 3
            //
            bOut             = new MemoryStream();
            messageGenerator = new PgpMessageGenerator(bOut);
            using (var compressedGenerator = messageGenerator.CreateCompressed(PgpCompressionAlgorithm.Zip))
                using (var signingGenerator = compressedGenerator.CreateSigned(PgpSignatureType.BinaryDocument, pgpPrivKey, PgpHashAlgorithm.Sha1, version: 3))
                    using (var literalStream = signingGenerator.CreateLiteral(PgpDataFormat.Binary, "_CONSOLE", testDateTime))
                    {
                        literalStream.Write(dataBytes);
                    }

            //
            // verify generated signature
            //
            bOut.Position     = 0;
            compressedMessage = (PgpCompressedMessage)PgpMessage.ReadMessage(bOut);
            signedMessage     = (PgpSignedMessage)compressedMessage.ReadMessage();
            literalMessage    = (PgpLiteralMessage)signedMessage.ReadMessage();
            Assert.AreEqual(testDateTime, literalMessage.ModificationTime);
            literalMessage.GetStream().CopyTo(Stream.Null);
            Assert.IsTrue(signedMessage.Verify(secretKey));

            //
            // extract PGP 8 private key
            //
            pgpPriv = new PgpSecretKeyRing(pgp8Key);

            secretKey = pgpPriv.GetSecretKey();

            pgpPrivKey = secretKey.ExtractPrivateKey(pgp8Pass);

            //
            // other sig tests
            //
            PerformTestSig(PgpHashAlgorithm.Sha256, secretKey, pgpPrivKey);
            PerformTestSig(PgpHashAlgorithm.Sha384, secretKey, pgpPrivKey);
            PerformTestSig(PgpHashAlgorithm.Sha512, secretKey, pgpPrivKey);
        }
        /// <summary>
        /// Create a file with PGP clear text signature. See documentation at https://github.com/CommunityHiQ/Frends.Community.PgpClearTextSignature Returns: Object {string FilePath}
        /// </summary>
        public static Result PGPClearTextSignFile(Input input)
        {
            HashAlgorithmTag digest;

            if (input.HashFunction == HashFunctionType.MD5)
            {
                digest = HashAlgorithmTag.MD5;
            }
            else if (input.HashFunction == HashFunctionType.RipeMD160)
            {
                digest = HashAlgorithmTag.RipeMD160;
            }
            else if (input.HashFunction == HashFunctionType.Sha1)
            {
                digest = HashAlgorithmTag.Sha1;
            }
            else if (input.HashFunction == HashFunctionType.Sha224)
            {
                digest = HashAlgorithmTag.Sha224;
            }
            else if (input.HashFunction == HashFunctionType.Sha384)
            {
                digest = HashAlgorithmTag.Sha384;
            }
            else if (input.HashFunction == HashFunctionType.Sha512)
            {
                digest = HashAlgorithmTag.Sha512;
            }
            else
            {
                digest = HashAlgorithmTag.Sha256;
            }

            Stream privateKeyStream = File.OpenRead(input.PrivateKeyFile);

            PgpSecretKey                   pgpSecKey  = ReadSecretKey(privateKeyStream);
            PgpPrivateKey                  pgpPrivKey = pgpSecKey.ExtractPrivateKey(input.Password.ToCharArray());
            PgpSignatureGenerator          sGen       = new PgpSignatureGenerator(pgpSecKey.PublicKey.Algorithm, digest);
            PgpSignatureSubpacketGenerator spGen      = new PgpSignatureSubpacketGenerator();

            sGen.InitSign(PgpSignature.CanonicalTextDocument, pgpPrivKey);

            IEnumerator enumerator = pgpSecKey.PublicKey.GetUserIds().GetEnumerator();

            if (enumerator.MoveNext())
            {
                spGen.SetSignerUserId(false, (string)enumerator.Current);
                sGen.SetHashedSubpackets(spGen.Generate());
            }

            Stream fIn          = File.OpenRead(input.InputFile);
            Stream outputStream = File.Create(input.OutputFile);

            ArmoredOutputStream aOut = new ArmoredOutputStream(outputStream);

            aOut.BeginClearText(digest);

            //
            // note the last \n/\r/\r\n in the file is ignored
            //
            MemoryStream lineOut   = new MemoryStream();
            int          lookAhead = ReadInputLine(lineOut, fIn);

            ProcessLine(aOut, sGen, lineOut.ToArray());

            if (lookAhead != -1)
            {
                do
                {
                    lookAhead = ReadInputLine(lineOut, lookAhead, fIn);

                    sGen.Update((byte)'\r');
                    sGen.Update((byte)'\n');

                    ProcessLine(aOut, sGen, lineOut.ToArray());
                }while (lookAhead != -1);
            }

            fIn.Close();

            aOut.EndClearText();

            BcpgOutputStream bOut = new BcpgOutputStream(aOut);

            sGen.Generate().Encode(bOut);

            aOut.Close();
            outputStream.Close();

            Result ret = new Result
            {
                FilePath = input.OutputFile
            };

            return(ret);
        }
예제 #28
0
        private static void DecryptPgp(Stream input, Stream output, Stream key, char[] password)
        {
            try
            {
                PgpObjectFactory pgpObjectFactory = new PgpObjectFactory(PgpUtilities.GetDecoderStream(input));
                PgpObject        pgpObject        = pgpObjectFactory.NextPgpObject();

                // The first object might be a PGP marker packet
                PgpEncryptedDataList pgpEncryptedDataList;
                if (pgpObject is PgpEncryptedDataList)
                {
                    pgpEncryptedDataList = (PgpEncryptedDataList)pgpObject;
                }
                else
                {
                    pgpEncryptedDataList = (PgpEncryptedDataList)pgpObjectFactory.NextPgpObject();
                }

                // Find private key for decryption
                PgpPrivateKey             privateKey                = null;
                PgpSecretKeyRingBundle    pgpSecretKeyRing          = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(key));
                PgpPublicKeyEncryptedData pgpPublicKeyEncryptedData = null;
                foreach (PgpPublicKeyEncryptedData pked in pgpEncryptedDataList.GetEncryptedDataObjects())
                {
                    PgpSecretKey pgpDescretKey = pgpSecretKeyRing.GetSecretKey(pked.KeyId);
                    privateKey = pgpDescretKey.ExtractPrivateKey(password);

                    if (privateKey != null)
                    {
                        pgpPublicKeyEncryptedData = pked;
                        break;
                    }
                }

                if (privateKey == null)
                {
                    throw new ArgumentException("Private key for decryption not found.");
                }

                Stream decrypted = pgpPublicKeyEncryptedData.GetDataStream(privateKey);
                pgpObjectFactory = new PgpObjectFactory(decrypted);
                pgpObject        = pgpObjectFactory.NextPgpObject();

                if (pgpObject is PgpCompressedData)
                {
                    PgpCompressedData pgpCompressedData = (PgpCompressedData)pgpObject;
                    pgpObjectFactory = new PgpObjectFactory(pgpCompressedData.GetDataStream());
                    pgpObject        = pgpObjectFactory.NextPgpObject();
                }

                if (pgpObject is PgpLiteralData)
                {
                    PgpLiteralData pgpLiteralData = (PgpLiteralData)pgpObject;
                    Stream         literal        = pgpLiteralData.GetInputStream();
                    Streams.PipeAll(literal, output);
                }
                else if (pgpObject is PgpOnePassSignatureList)
                {
                    throw new PgpException("Encrypted message contains a signed message, not a literal data.");
                }
                else
                {
                    throw new PgpException("Message is not a simple encrypted file, type is unknown.");
                }

                if (pgpPublicKeyEncryptedData.IsIntegrityProtected())
                {
                    if (!pgpPublicKeyEncryptedData.Verify())
                    {
                        Console.Error.WriteLine("Message failed integrity check.");
                    }
                    else
                    {
                        Console.Error.WriteLine("Message integrity check passed.");
                    }
                }
                else
                {
                    Console.Error.WriteLine("No message integrity check.");
                }

                Console.WriteLine("OpenPGP decryption successfull.");
            }
            catch (PgpException ex)
            {
                Console.Error.WriteLine(ex);

                Exception pgpInnerException = ex.InnerException;
                if (pgpInnerException != null)
                {
                    Console.Error.WriteLine(pgpInnerException.Message);
                    Console.Error.WriteLine(pgpInnerException.StackTrace);
                }
            }
        }
예제 #29
0
        public void SignAndEncryptFile(string strActualFileName, string strEmbeddedFileName,
                                       System.IO.Stream strmKeyIn, long lngKeyId, System.IO.Stream strmOutputStream,
                                       char[] szPassword, bool bArmor, bool bWithIntegrityCheck, PgpPublicKey PGP_PublicKey)
        {
            const int iBUFFER_SIZE = 1 << 16; // should always be power of 2

            if (bArmor)
            {
                strmOutputStream = new ArmoredOutputStream(strmOutputStream);
            }

            // Init encrypted data generator
            PgpEncryptedDataGenerator PGP_EncryptedDataGenerator = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, bWithIntegrityCheck, new SecureRandom());

            PGP_EncryptedDataGenerator.AddMethod(PGP_PublicKey);
            System.IO.Stream strmEncryptedOut = PGP_EncryptedDataGenerator.Open(strmOutputStream, new byte[iBUFFER_SIZE]);

            // Init compression
            PgpCompressedDataGenerator PGP_CompressedDataGenerator = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip);

            System.IO.Stream strmCompressedOut = PGP_CompressedDataGenerator.Open(strmEncryptedOut);

            // Init signature
            PgpSecretKeyRingBundle PGP_SecretKeyBundle = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(strmKeyIn));
            PgpSecretKey           PGP_SecretKey       = PGP_SecretKeyBundle.GetSecretKey(lngKeyId);

            if (PGP_SecretKey == null)
            {
                throw new System.ArgumentException(lngKeyId.ToString("X") + " could not be found in specified key ring bundle.", "keyId");
            }

            PgpPrivateKey         PGP_PrivateKey         = PGP_SecretKey.ExtractPrivateKey(szPassword);
            PgpSignatureGenerator PGP_SignatureGenerator = new PgpSignatureGenerator(PGP_SecretKey.PublicKey.Algorithm, HashAlgorithmTag.Sha1);

            PGP_SignatureGenerator.InitSign(PgpSignature.BinaryDocument, PGP_PrivateKey);

            foreach (string strUserId in PGP_SecretKey.PublicKey.GetUserIds())
            {
                PgpSignatureSubpacketGenerator PGP_SignatureSubpacketGenerator = new PgpSignatureSubpacketGenerator();
                PGP_SignatureSubpacketGenerator.SetSignerUserId(false, strUserId);
                PGP_SignatureGenerator.SetHashedSubpackets(PGP_SignatureSubpacketGenerator.Generate());
                // Just the first one!
                break;
            }
            PGP_SignatureGenerator.GenerateOnePassVersion(false).Encode(strmCompressedOut);

            // Create the Literal Data generator output stream
            PgpLiteralDataGenerator PGP_LiteralDataGenerator = new PgpLiteralDataGenerator();

            System.IO.FileInfo fiEmbeddedFile = new System.IO.FileInfo(strEmbeddedFileName);
            System.IO.FileInfo fiActualFile   = new System.IO.FileInfo(strActualFileName);
            // TODO: Use lastwritetime from source file
            System.IO.Stream strmLiteralOut = PGP_LiteralDataGenerator.Open(strmCompressedOut, PgpLiteralData.Binary,
                                                                            fiEmbeddedFile.Name, fiActualFile.LastWriteTime, new byte[iBUFFER_SIZE]);

            // Open the input file
            System.IO.FileStream strmInputStream = fiActualFile.OpenRead();

            byte[] baBuffer = new byte[iBUFFER_SIZE];
            int    iReadLength;

            while ((iReadLength = strmInputStream.Read(baBuffer, 0, baBuffer.Length)) > 0)
            {
                strmLiteralOut.Write(baBuffer, 0, iReadLength);
                PGP_SignatureGenerator.Update(baBuffer, 0, iReadLength);
            }

            strmLiteralOut.Close();
            PGP_LiteralDataGenerator.Close();
            PGP_SignatureGenerator.Generate().Encode(strmCompressedOut);
            strmCompressedOut.Close();
            PGP_CompressedDataGenerator.Close();
            strmEncryptedOut.Close();
            PGP_EncryptedDataGenerator.Close();
            strmInputStream.Close();

            if (bArmor)
            {
                strmOutputStream.Close();
            }
        }
예제 #30
0
        public override void PerformTest()
        {
            //
            // RSA tests
            //
            PgpSecretKeyRing pgpPriv    = new PgpSecretKeyRing(rsaKeyRing);
            PgpSecretKey     secretKey  = pgpPriv.GetSecretKey();
            PgpPrivateKey    pgpPrivKey = secretKey.ExtractPrivateKey(rsaPass);

            try
            {
                doTestSig(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey);

                Fail("RSA wrong key test failed.");
            }
            catch (PgpException)
            {
                // expected
            }

            try
            {
                doTestSigV3(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey);

                Fail("RSA V3 wrong key test failed.");
            }
            catch (PgpException)
            {
                // expected
            }

            //
            // certifications
            //
            PgpSignatureGenerator sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1);

            sGen.InitSign(PgpSignature.KeyRevocation, pgpPrivKey);

            PgpSignature sig = sGen.GenerateCertification(secretKey.PublicKey);

            sig.InitVerify(secretKey.PublicKey);

            if (!sig.VerifyCertification(secretKey.PublicKey))
            {
                Fail("revocation verification failed.");
            }

            PgpSecretKeyRing pgpDSAPriv    = new PgpSecretKeyRing(dsaKeyRing);
            PgpSecretKey     secretDSAKey  = pgpDSAPriv.GetSecretKey();
            PgpPrivateKey    pgpPrivDSAKey = secretDSAKey.ExtractPrivateKey(dsaPass);

            sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1);

            sGen.InitSign(PgpSignature.SubkeyBinding, pgpPrivDSAKey);

            PgpSignatureSubpacketGenerator unhashedGen = new PgpSignatureSubpacketGenerator();
            PgpSignatureSubpacketGenerator hashedGen   = new PgpSignatureSubpacketGenerator();

            hashedGen.SetSignatureExpirationTime(false, TEST_EXPIRATION_TIME);
            hashedGen.SetSignerUserId(true, TEST_USER_ID);
            hashedGen.SetPreferredCompressionAlgorithms(false, PREFERRED_COMPRESSION_ALGORITHMS);
            hashedGen.SetPreferredHashAlgorithms(false, PREFERRED_HASH_ALGORITHMS);
            hashedGen.SetPreferredSymmetricAlgorithms(false, PREFERRED_SYMMETRIC_ALGORITHMS);

            sGen.SetHashedSubpackets(hashedGen.Generate());
            sGen.SetUnhashedSubpackets(unhashedGen.Generate());

            sig = sGen.GenerateCertification(secretDSAKey.PublicKey, secretKey.PublicKey);

            byte[] sigBytes = sig.GetEncoded();

            PgpObjectFactory f = new PgpObjectFactory(sigBytes);

            sig = ((PgpSignatureList)f.NextPgpObject())[0];

            sig.InitVerify(secretDSAKey.PublicKey);

            if (!sig.VerifyCertification(secretDSAKey.PublicKey, secretKey.PublicKey))
            {
                Fail("subkey binding verification failed.");
            }

            PgpSignatureSubpacketVector hashedPcks   = sig.GetHashedSubPackets();
            PgpSignatureSubpacketVector unhashedPcks = sig.GetUnhashedSubPackets();

            if (hashedPcks.Count != 6)
            {
                Fail("wrong number of hashed packets found.");
            }

            if (unhashedPcks.Count != 1)
            {
                Fail("wrong number of unhashed packets found.");
            }

            if (!hashedPcks.GetSignerUserId().Equals(TEST_USER_ID))
            {
                Fail("test userid not matching");
            }

            if (hashedPcks.GetSignatureExpirationTime() != TEST_EXPIRATION_TIME)
            {
                Fail("test signature expiration time not matching");
            }

            if (unhashedPcks.GetIssuerKeyId() != secretDSAKey.KeyId)
            {
                Fail("wrong issuer key ID found in certification");
            }

            int[] prefAlgs = hashedPcks.GetPreferredCompressionAlgorithms();
            preferredAlgorithmCheck("compression", PREFERRED_COMPRESSION_ALGORITHMS, prefAlgs);

            prefAlgs = hashedPcks.GetPreferredHashAlgorithms();
            preferredAlgorithmCheck("hash", PREFERRED_HASH_ALGORITHMS, prefAlgs);

            prefAlgs = hashedPcks.GetPreferredSymmetricAlgorithms();
            preferredAlgorithmCheck("symmetric", PREFERRED_SYMMETRIC_ALGORITHMS, prefAlgs);

            SignatureSubpacketTag[] criticalHashed = hashedPcks.GetCriticalTags();

            if (criticalHashed.Length != 1)
            {
                Fail("wrong number of critical packets found.");
            }

            if (criticalHashed[0] != SignatureSubpacketTag.SignerUserId)
            {
                Fail("wrong critical packet found in tag list.");
            }

            //
            // no packets passed
            //
            sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1);

            sGen.InitSign(PgpSignature.SubkeyBinding, pgpPrivDSAKey);

            sGen.SetHashedSubpackets(null);
            sGen.SetUnhashedSubpackets(null);

            sig = sGen.GenerateCertification(TEST_USER_ID, secretKey.PublicKey);

            sig.InitVerify(secretDSAKey.PublicKey);

            if (!sig.VerifyCertification(TEST_USER_ID, secretKey.PublicKey))
            {
                Fail("subkey binding verification failed.");
            }

            hashedPcks = sig.GetHashedSubPackets();

            if (hashedPcks.Count != 1)
            {
                Fail("found wrong number of hashed packets");
            }

            unhashedPcks = sig.GetUnhashedSubPackets();

            if (unhashedPcks.Count != 1)
            {
                Fail("found wrong number of unhashed packets");
            }

            try
            {
                sig.VerifyCertification(secretKey.PublicKey);

                Fail("failed to detect non-key signature.");
            }
            catch (InvalidOperationException)
            {
                // expected
            }

            //
            // override hash packets
            //
            sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1);

            sGen.InitSign(PgpSignature.SubkeyBinding, pgpPrivDSAKey);

            hashedGen = new PgpSignatureSubpacketGenerator();

            DateTime creationTime = new DateTime(1973, 7, 27);

            hashedGen.SetSignatureCreationTime(false, creationTime);

            sGen.SetHashedSubpackets(hashedGen.Generate());

            sGen.SetUnhashedSubpackets(null);

            sig = sGen.GenerateCertification(TEST_USER_ID, secretKey.PublicKey);

            sig.InitVerify(secretDSAKey.PublicKey);

            if (!sig.VerifyCertification(TEST_USER_ID, secretKey.PublicKey))
            {
                Fail("subkey binding verification failed.");
            }

            hashedPcks = sig.GetHashedSubPackets();

            if (hashedPcks.Count != 1)
            {
                Fail("found wrong number of hashed packets in override test");
            }

            if (!hashedPcks.HasSubpacket(SignatureSubpacketTag.CreationTime))
            {
                Fail("hasSubpacket test for creation time failed");
            }

            DateTime sigCreationTime = hashedPcks.GetSignatureCreationTime();

            if (!sigCreationTime.Equals(creationTime))
            {
                Fail("creation of overridden date failed.");
            }

            prefAlgs = hashedPcks.GetPreferredCompressionAlgorithms();
            preferredAlgorithmCheck("compression", NO_PREFERENCES, prefAlgs);

            prefAlgs = hashedPcks.GetPreferredHashAlgorithms();
            preferredAlgorithmCheck("hash", NO_PREFERENCES, prefAlgs);

            prefAlgs = hashedPcks.GetPreferredSymmetricAlgorithms();
            preferredAlgorithmCheck("symmetric", NO_PREFERENCES, prefAlgs);

            if (hashedPcks.GetKeyExpirationTime() != 0)
            {
                Fail("unexpected key expiration time found");
            }

            if (hashedPcks.GetSignatureExpirationTime() != 0)
            {
                Fail("unexpected signature expiration time found");
            }

            if (hashedPcks.GetSignerUserId() != null)
            {
                Fail("unexpected signer user ID found");
            }

            criticalHashed = hashedPcks.GetCriticalTags();

            if (criticalHashed.Length != 0)
            {
                Fail("critical packets found when none expected");
            }

            unhashedPcks = sig.GetUnhashedSubPackets();

            if (unhashedPcks.Count != 1)
            {
                Fail("found wrong number of unhashed packets in override test");
            }

            //
            // general signatures
            //
            doTestSig(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha256, secretKey.PublicKey, pgpPrivKey);
            doTestSig(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha384, secretKey.PublicKey, pgpPrivKey);
            doTestSig(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha512, secretKey.PublicKey, pgpPrivKey);
            doTestSigV3(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey);
            doTestTextSig(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA_WITH_CRLF, TEST_DATA_WITH_CRLF);
            doTestTextSig(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA, TEST_DATA_WITH_CRLF);
            doTestTextSigV3(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA_WITH_CRLF, TEST_DATA_WITH_CRLF);
            doTestTextSigV3(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA, TEST_DATA_WITH_CRLF);

            //
            // DSA Tests
            //
            pgpPriv    = new PgpSecretKeyRing(dsaKeyRing);
            secretKey  = pgpPriv.GetSecretKey();
            pgpPrivKey = secretKey.ExtractPrivateKey(dsaPass);

            try
            {
                doTestSig(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey);

                Fail("DSA wrong key test failed.");
            }
            catch (PgpException)
            {
                // expected
            }

            try
            {
                doTestSigV3(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey);

                Fail("DSA V3 wrong key test failed.");
            }
            catch (PgpException)
            {
                // expected
            }

            doTestSig(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey);
            doTestSigV3(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey);
            doTestTextSig(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA_WITH_CRLF, TEST_DATA_WITH_CRLF);
            doTestTextSig(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA, TEST_DATA_WITH_CRLF);
            doTestTextSigV3(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA_WITH_CRLF, TEST_DATA_WITH_CRLF);
            doTestTextSigV3(PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1, secretKey.PublicKey, pgpPrivKey, TEST_DATA, TEST_DATA_WITH_CRLF);

            // special cases
            //
            doTestMissingSubpackets(nullPacketsSubKeyBinding);

            doTestMissingSubpackets(generateV3BinarySig(pgpPrivKey, PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1));

            // keyflags
            doTestKeyFlagsValues();
        }
예제 #31
0
		private static byte[] SignPublicKey(
			PgpSecretKey	secretKey,
			string			secretKeyPass,
			PgpPublicKey	keyToBeSigned,
			string			notationName,
			string			notationValue,
			bool			armor)
		{
			Stream os = new MemoryStream();
			if (armor)
			{
				os = new ArmoredOutputStream(os);
			}

			PgpPrivateKey pgpPrivKey = secretKey.ExtractPrivateKey(
				secretKeyPass.ToCharArray());

			PgpSignatureGenerator sGen = new PgpSignatureGenerator(
				secretKey.PublicKey.Algorithm, HashAlgorithmTag.Sha1);

			sGen.InitSign(PgpSignature.DirectKey, pgpPrivKey);

			BcpgOutputStream bOut = new BcpgOutputStream(os);

			sGen.GenerateOnePassVersion(false).Encode(bOut);

			PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator();

			bool isHumanReadable = true;

			spGen.SetNotationData(true, isHumanReadable, notationName, notationValue);

			PgpSignatureSubpacketVector packetVector = spGen.Generate();
			sGen.SetHashedSubpackets(packetVector);

			bOut.Flush();

			if (armor)
			{
				os.Close();
			}

			return PgpPublicKey.AddCertification(keyToBeSigned, sGen.Generate()).GetEncoded();
		}
예제 #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();
        }