Exemplo n.º 1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="inputStream"></param>
        /// <param name="outFile"></param>
        /// <param name="passPhrase"></param>
        public static void DecryptFile(
            Stream inputStream,
            string outFile,
            char[] passPhrase)
        {
            inputStream = PgpUtilities.GetDecoderStream(inputStream);

            var pgpF = new PgpObjectFactory(inputStream);
            var o    = pgpF.NextPgpObject();

            //
            // the first object might be a PGP marker packet.
            //
            var enc = o as PgpEncryptedDataList;

            if (enc == null)
            {
                enc = (PgpEncryptedDataList)pgpF.NextPgpObject();
            }

            var pbe   = (PgpPbeEncryptedData)enc[0];
            var clear = pbe.GetDataStream(passPhrase);

            var pgpFact = new PgpObjectFactory(clear);

            //
            // if we're trying to read a file generated by someone other than us
            // the data might not be compressed, so we check the return type from
            // the factory and behave accordingly.
            //
            o = pgpFact.NextPgpObject();
            if (o is PgpCompressedData)
            {
                var cData = (PgpCompressedData)o;
                pgpFact = new PgpObjectFactory(cData.GetDataStream());
                o       = pgpFact.NextPgpObject();
            }
            var    ld   = (PgpLiteralData)o;
            var    unc  = ld.GetInputStream();
            Stream fOut = File.Create(outFile);

            Streams.PipeAll(unc, fOut);
            fOut.Close();

            if (pbe.IsIntegrityProtected())
            {
                if (!pbe.Verify())
                {
                    Console.Error.WriteLine("Message failed integrity check");
                }
                else
                {
                    Console.Error.WriteLine("Message integrity check passed");
                }
            }
            else
            {
                Console.Error.WriteLine("No message integrity check");
            }
        }
Exemplo n.º 2
0
        public override void PerformTest()
        {
            //
            // test encrypted message
            //
            PgpObjectFactory pgpFact = new PgpObjectFactory(message1);

            if (pgpFact.NextPgpObject() is PgpMarker)
            {
                if (pgpFact.NextPgpObject() is PgpEncryptedDataList)
                {
                    return;
                }
                else
                {
                    Fail("error processing after marker.");
                }
            }

            // TODO Does this even get called?
            pgpFact = new PgpObjectFactory(message2);

            if (pgpFact.NextPgpObject() is PgpMarker)
            {
                if (!(pgpFact.NextPgpObject() is PgpEncryptedDataList))
                {
                    return;
                }
                else
                {
                    Fail("error processing after marker.");
                }
            }
        }
Exemplo n.º 3
0
        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]));
        }
Exemplo n.º 4
0
 /// <summary>
 /// Extract PgpPublicKeyEncryptedData from PgpObjectFactory created from source encrypted stream
 /// </summary>
 public static PgpPublicKeyEncryptedData GetEncryptedData(this PgpObjectFactory factory)
 {
     try
     {
         // Extract first PGP object from factory:
         var obj = factory.NextPgpObject();
         while (obj != null)
         {
             // If object is an encrypted data list, extract first encrypted data object:
             if (obj is PgpEncryptedDataList list)
             {
                 return(list
                        .GetEncryptedDataObjects()
                        .Cast <PgpPublicKeyEncryptedData>()
                        .FirstOrDefault());
             }
             // Otherwise, move on to next object:
             obj = factory.NextPgpObject();
         }
         // If this point is reached, encrypted data list was never encountered
         return(null);
     }
     catch (Exception ex)
     {
         // Note that NextPgpObject will throw IOException if unknown object type encountered
         // prior to capturing a PgpEncryptedDataList object (likely what happened here)
         throw new ArgumentException("Failed to extract PGP-encrypted data", ex);
     }
 }
Exemplo n.º 5
0
        public static void Decrypt(Stream inputStream, Stream privateKeyStream, string passPhrase, string outputFilePath)
        {
            var objectFactory = new PgpObjectFactory(PgpUtilities.GetDecoderStream(inputStream));
            var secretKeyRing = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(privateKeyStream));

            PgpEncryptedDataList encryptedDataList = (objectFactory.NextPgpObject() as PgpEncryptedDataList)
                                                     ?? (PgpEncryptedDataList)objectFactory.NextPgpObject();

            PgpObjectFactory plainFact = RetrievePgpObjectFactory(encryptedDataList, secretKeyRing, passPhrase);
            PgpObject        message   = plainFact.NextPgpObject();

            if (message is PgpOnePassSignatureList)
            {
                throw new PgpException("Encrypted message contains a signed message - not literal data.");
            }

            if (message is PgpCompressedData)
            {
                DecryptCompressedData(message, outputFilePath);
            }
            else if (message is PgpLiteralData)
            {
                PipeStreamToFile(outputFilePath, (PgpLiteralData)message);
            }
            else
            {
                throw new PgpException("Message is not a simple encrypted file - type unknown.");
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// Retrieve cleartext literal packet data read from PgpObjectFactory (created from PgpEncryptedData
        /// combined with PgpPrivateKey) and write payload asynchronously into destination stream
        /// </summary>
        public static async Task WriteClearData(this PgpObjectFactory factory, Stream cleardest)
        {
            // Extract first PGP object from factory:
            var message = factory.NextPgpObject();

            while (message != null)
            {
                // If object is literal data, de-literalize to destination and exit:
                if (message is PgpLiteralData cleardata)
                {
                    using (var clearstream = cleardata.GetInputStream())
                    {
                        await clearstream.CopyToAsync(cleardest);

                        return;
                    }
                }
                // Otherwise if this is compressed data, we need to create a new object factory to
                // decompress data from compressed source and call this function recursively:
                else if (message is PgpCompressedData compresseddata)
                {
                    using (var compresseddatastream = compresseddata.GetDataStream())
                    {
                        await new PgpObjectFactory(compresseddatastream).WriteClearData(cleardest);
                        return;
                    }
                }
                // Otherwise continue on to next message object
                message = factory.NextPgpObject();
            }

            // If this point is reached, no literal packet was ever found
            throw new ArgumentException("Invalid PGP data (no payload found)");
        }
Exemplo n.º 7
0
        static void Decrypt(Stream encStream, Stream decryptStream)
        {
            PgpObjectFactory     pgpF = new PgpObjectFactory(PgpUtilities.GetDecoderStream(encStream));
            PgpObject            o    = pgpF.NextPgpObject();
            PgpEncryptedDataList enc;

            if (o is PgpEncryptedDataList)
            {
                enc = (PgpEncryptedDataList)o;
            }
            else
            {
                enc = (PgpEncryptedDataList)pgpF.NextPgpObject();
            }
            PgpPublicKeyEncryptedData pbe = null;

            foreach (PgpPublicKeyEncryptedData pked in enc.GetEncryptedDataObjects())
            {
                pbe = pked;
                break;
            }
            PgpObjectFactory plainFact = null;

            using (Stream clear = pbe.GetDataStream(PrivateKey))
            {
                plainFact = new PgpObjectFactory(clear);
            }
            PgpObject message = plainFact.NextPgpObject();

            if (message is PgpCompressedData)
            {
                var cData = (PgpCompressedData)message;
                PgpObjectFactory of;
                using (Stream compDataIn = cData.GetDataStream())
                {
                    of = new PgpObjectFactory(compDataIn);
                }
                message = of.NextPgpObject();
                if (message is PgpOnePassSignatureList)
                {
                    message = of.NextPgpObject();
                }
                PgpLiteralData Ld  = (PgpLiteralData)message;
                Stream         unc = Ld.GetInputStream();
                Streams.PipeAll(unc, decryptStream);
                return;
            }
            if (message is PgpLiteralData)
            {
                PgpLiteralData ld  = (PgpLiteralData)message;
                Stream         unc = ld.GetInputStream();
                Streams.PipeAll(unc, decryptStream);
                return;
            }
            if (message is PgpOnePassSignatureList)
            {
                throw new PgpException("PgpOnePassSignatureList");
            }
            throw new PgpException("Not a simple encrypted file");
        }
        public String DecryptKeycode(String privateKeyStr, String encryptedKeycode)
        {
            byte[] rawMessage = System.Text.Encoding.ASCII.GetBytes(encryptedKeycode);

            Stream inputStream = new MemoryStream(rawMessage);

            inputStream = PgpUtilities.GetDecoderStream(inputStream);

            PgpObjectFactory     pgpF = new PgpObjectFactory(inputStream);
            PgpEncryptedDataList enc  = null;
            PgpObject            o    = pgpF.NextPgpObject();

            //
            // the first object might be a PGP marker packet.
            //
            if (o is PgpEncryptedDataList)
            {
                enc = (PgpEncryptedDataList)o;
            }
            else
            {
                enc = (PgpEncryptedDataList)pgpF.NextPgpObject();
            }

            byte[]        decodedPrivateKey = System.Text.Encoding.ASCII.GetBytes(privateKeyStr);
            PgpPrivateKey key = null;

            Stream decodedStream             = PgpUtilities.GetDecoderStream(new MemoryStream(decodedPrivateKey));
            PgpSecretKeyRingBundle privRings = new PgpSecretKeyRingBundle(decodedStream);

            PgpPublicKeyEncryptedData dataObject = null;

            foreach (PgpPublicKeyEncryptedData encryptedData in enc.GetEncryptedDataObjects())
            {
                key        = FindKeyById(privRings, encryptedData.KeyId);
                dataObject = encryptedData;
            }

            if (key == null)
            {
                throw new SendSafely.Exceptions.InvalidKeyException("Can't find encryption key in key ring.");
            }

            Stream dataStream = dataObject.GetDataStream(key);

            PgpObjectFactory pgpFact = new PgpObjectFactory(dataStream);

            PgpLiteralData ld = (PgpLiteralData)pgpFact.NextPgpObject();

            Stream unc = ld.GetInputStream();

            String keycode;

            using (StreamReader reader = new StreamReader(unc, Encoding.UTF8))
            {
                keycode = reader.ReadToEnd();
            }

            return(keycode);
        }
Exemplo n.º 9
0
		public override void PerformTest()
        {
            //
            // test encrypted message
            //
            PgpObjectFactory pgpFact = new PgpObjectFactory(message1);

            if (pgpFact.NextPgpObject() is PgpMarker)
            {
                if (pgpFact.NextPgpObject() is PgpEncryptedDataList)
                {
                    return;
                }
                else
                {
                    Fail("error processing after marker.");
                }
            }

			// TODO Does this even get called?
			pgpFact = new PgpObjectFactory(message2);

            if (pgpFact.NextPgpObject() is PgpMarker)
            {
                if (!(pgpFact.NextPgpObject() is PgpEncryptedDataList))
                {
                    return;
                }
                else
                {
                    Fail("error processing after marker.");
                }
            }
        }
 public void decrypt(Stream input, string outputpath)
 {
     input = PgpUtilities.GetDecoderStream(input);
     try
     {
         PgpObjectFactory     pgpObjF = new PgpObjectFactory(input);
         PgpEncryptedDataList enc;
         PgpObject            obj = pgpObjF.NextPgpObject();
         if (obj is PgpEncryptedDataList)
         {
             enc = (PgpEncryptedDataList)obj;
         }
         else
         {
             enc = (PgpEncryptedDataList)pgpObjF.NextPgpObject();
         }
         PgpPrivateKey             privKey = pgpKeys.PrivateKey;
         PgpPublicKeyEncryptedData pbe     = null;
         foreach (PgpPublicKeyEncryptedData pked in enc.GetEncryptedDataObjects())
         {
             if (privKey != null)
             {
                 pbe = pked;
                 break;
             }
         }
         Stream           clear     = pbe.GetDataStream(privKey);
         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();
                 PgpLiteralData Ld = null;
                 Ld = (PgpLiteralData)message;
                 Stream output = File.Create(outputpath + "\\" + Ld.FileName);
                 Stream unc    = Ld.GetInputStream();
                 Streams.PipeAll(unc, output);
             }
             else
             {
                 PgpLiteralData Ld = null;
                 Ld = (PgpLiteralData)message;
                 Stream output = File.Create(outputpath + "\\" + Ld.FileName);
                 Stream unc    = Ld.GetInputStream();
                 Streams.PipeAll(unc, output);
             }
         }
     }
     catch (Exception e)
     {
         throw new Exception(e.Message);
     }
 }
Exemplo n.º 11
0
        /// <summary>
        ///     Verifies the specified signature using the specified public key.
        /// </summary>
        /// <param name="input">The signature to verify.</param>
        /// <param name="publicKey">The public key with which to decode the signature.</param>
        /// <returns>A byte array containing the message contained within the signature.</returns>
        /// <exception cref="PgpDataValidationException">
        ///     Thrown when the specified signature is invalid, or if an exception is encountered while validating.
        /// </exception>
        public static byte[] Verify(string input, string publicKey)
        {
            // create input streams from
            Stream inputStream     = new MemoryStream(Encoding.UTF8.GetBytes(input ?? string.Empty));
            Stream publicKeyStream = new MemoryStream(Encoding.UTF8.GetBytes(publicKey ?? string.Empty));

            // enclose all operations in a try/catch. if we encounter any exceptions verification fails.
            try
            {
                // lines taken pretty much verbatim from the bouncycastle example. not sure what it all does.
                inputStream = PgpUtilities.GetDecoderStream(inputStream);

                PgpObjectFactory  pgpFact = new PgpObjectFactory(inputStream);
                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();
                PgpPublicKeyRingBundle pgpRing = new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(publicKeyStream));
                PgpPublicKey           key     = pgpRing.GetPublicKey(ops.KeyId);

                // set up a memorystream to contain the message contained within the signature
                MemoryStream memoryStream = new MemoryStream();

                ops.InitVerify(key);

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

                // save the contents of the memorystream to a byte array
                byte[] retVal = memoryStream.ToArray();

                memoryStream.Close();

                PgpSignatureList p3       = (PgpSignatureList)pgpFact.NextPgpObject();
                PgpSignature     firstSig = p3[0];

                // verify.
                if (ops.Verify(firstSig))
                {
                    return(retVal);
                }
                else
                {
                    throw new PgpDataValidationException();
                }
            }
            catch (Exception)
            {
                throw new PgpDataValidationException();
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// Verifies a PGP signature. See documentation at https://github.com/CommunityHiQ/Frends.Community.PgpVerifySignature Returns: Object {string FilePath, Boolean Verified}
        /// </summary>
        public static Result PGPVerifySignFile(Input input)
        {
            try
            {
                Stream inputStream = PgpUtilities.GetDecoderStream(File.OpenRead(input.InputFile));

                PgpObjectFactory        pgpFact = new PgpObjectFactory(inputStream);
                PgpOnePassSignatureList p1      = (PgpOnePassSignatureList)pgpFact.NextPgpObject();
                PgpOnePassSignature     ops     = p1[0];

                PgpLiteralData         p2      = (PgpLiteralData)pgpFact.NextPgpObject();
                Stream                 dIn     = p2.GetInputStream();
                PgpPublicKeyRingBundle pgpRing = new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(File.OpenRead(input.PublicKeyFile)));
                PgpPublicKey           key     = pgpRing.GetPublicKey(ops.KeyId);

                string fosPath;
                if (String.IsNullOrWhiteSpace(input.OutputFolder))
                {
                    fosPath = Path.Combine(Path.GetDirectoryName(input.InputFile), p2.FileName);
                }
                else
                {
                    fosPath = Path.Combine(input.OutputFolder, p2.FileName);
                }
                Stream fos = File.Create(fosPath);

                ops.InitVerify(key);

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

                PgpSignatureList p3       = (PgpSignatureList)pgpFact.NextPgpObject();
                PgpSignature     firstSig = p3[0];
                bool             verified = ops.Verify(firstSig);

                Result ret = new Result
                {
                    FilePath = fosPath,
                    Verified = verified
                };

                return(ret);
            }
            catch (Exception e)
            {
                Result ret = new Result
                {
                    FilePath = input.OutputFolder,
                    Verified = false
                };

                return(ret);
            }
        }
Exemplo n.º 13
0
        private void verifySignature(
            byte[] encodedSig,
            HashAlgorithmTag hashAlgorithm,
            PgpPublicKey pubKey,
            byte[] original)
        {
            PgpObjectFactory        pgpFact = new PgpObjectFactory(encodedSig);
            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();
            PgpSignature     sig = p3[0];

            DateTime creationTime = sig.CreationTime;

            // Check creationTime is recent
            if (creationTime.CompareTo(DateTime.UtcNow) > 0 ||
                creationTime.CompareTo(DateTime.UtcNow.AddMinutes(-10)) < 0)
            {
                Fail("bad creation time in signature: " + creationTime);
            }

            if (sig.KeyId != pubKey.KeyId)
            {
                Fail("key id mismatch in signature");
            }

            if (!ops.Verify(sig))
            {
                Fail("Failed generated signature check - " + hashAlgorithm);
            }

            sig.InitVerify(pubKey);

            for (int i = 0; i != original.Length; i++)
            {
                sig.Update(original[i]);
            }

            sig.Update(original);

            if (!sig.Verify())
            {
                Fail("Failed generated signature check against original data");
            }
        }
 private static PgpObject checkforOnePassSignatureList(PgpObject message, PgpObjectFactory compressedFactory)
 {
     message = compressedFactory.NextPgpObject();
     if (message is PgpOnePassSignatureList)
     {
         message = compressedFactory.NextPgpObject();
     }
     return(message);
 }
Exemplo n.º 15
0
        public string DecryptKeycode(string privateKeyStr, string encryptedKeycode)
        {
            var rawMessage = Encoding.ASCII.GetBytes(encryptedKeycode);

            Stream inputStream = new MemoryStream(rawMessage);

            inputStream = PgpUtilities.GetDecoderStream(inputStream);

            var pgpF = new PgpObjectFactory(inputStream);
            PgpEncryptedDataList enc;
            var o = pgpF.NextPgpObject();

            //
            // the first object might be a PGP marker packet.
            //
            if (o is PgpEncryptedDataList list)
            {
                enc = list;
            }
            else
            {
                enc = (PgpEncryptedDataList)pgpF.NextPgpObject();
            }

            var           decodedPrivateKey = Encoding.ASCII.GetBytes(privateKeyStr);
            PgpPrivateKey key = null;

            var decodedStream = PgpUtilities.GetDecoderStream(new MemoryStream(decodedPrivateKey));
            var privRings     = new PgpSecretKeyRingBundle(decodedStream);

            PgpPublicKeyEncryptedData dataObject = null;

            foreach (PgpPublicKeyEncryptedData encryptedData in enc.GetEncryptedDataObjects())
            {
                key        = FindKeyById(privRings, encryptedData.KeyId);
                dataObject = encryptedData;
            }

            if (key == null)
            {
                throw new InvalidKeyException("Can't find encryption key in key ring.");
            }

            var dataStream = dataObject.GetDataStream(key);

            var pgpFact = new PgpObjectFactory(dataStream);

            var ld = (PgpLiteralData)pgpFact.NextPgpObject();

            var unc = ld.GetInputStream();

            using var reader = new StreamReader(unc, Encoding.UTF8);
            var keycode = reader.ReadToEnd();

            return(keycode);
        }
Exemplo n.º 16
0
        public static Stream Decrypt(Stream input, String privateKeyPath, String privateKeyPass)
        {
            input = PgpUtilities.GetDecoderStream(input);
            try
            {
                var pgpObjF = new PgpObjectFactory(input);
                PgpEncryptedDataList enc;
                var obj = pgpObjF.NextPgpObject();
                if (obj is PgpEncryptedDataList)
                {
                    enc = (PgpEncryptedDataList)obj;
                }
                else
                {
                    enc = (PgpEncryptedDataList)pgpObjF.NextPgpObject();
                }

                foreach (PgpPublicKeyEncryptedData pbe in enc.GetEncryptedDataObjects().Cast <PgpPublicKeyEncryptedData>())
                {
                    var privKey = GetPrivateKey(privateKeyPath, pbe.KeyId, privateKeyPass);
                    if (privKey == null)
                    {
                        continue;
                    }
                    Stream clear;
                    clear = pbe.GetDataStream(privKey);
                    var plainFact = new PgpObjectFactory(clear);
                    var message   = plainFact.NextPgpObject();
                    if (message is PgpCompressedData)
                    {
                        var cData      = (PgpCompressedData)message;
                        var compDataIn = cData.GetDataStream();
                        var o          = new PgpObjectFactory(compDataIn);
                        message = o.NextPgpObject();
                        if (message is PgpOnePassSignatureList)
                        {
                            message = o.NextPgpObject();
                            PgpLiteralData Ld = null;
                            Ld = (PgpLiteralData)message;
                            return(Ld.GetInputStream());
                        }
                        else
                        {
                            PgpLiteralData Ld = null;
                            Ld = (PgpLiteralData)message;
                            return(Ld.GetInputStream());
                        }
                    }
                }
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            return(null);
        }
Exemplo n.º 17
0
        public static bool Verify(string hash, string signature, string publicKey)
        {
            try {
                var signatureStream = new MemoryStream(Encoding.ASCII.GetBytes(signature));
                var decoderStream   = PgpUtilities.GetDecoderStream(signatureStream);

                PgpObjectFactory pgpObjectFactory = new PgpObjectFactory(decoderStream);

                PgpOnePassSignatureList signatureList    = (PgpOnePassSignatureList)pgpObjectFactory.NextPgpObject();
                PgpOnePassSignature     onePassSignature = signatureList[0];

                PgpLiteralData         literalData   = (PgpLiteralData)pgpObjectFactory.NextPgpObject();
                Stream                 literalStream = literalData.GetInputStream();
                Stream                 keyFile       = new MemoryStream(Encoding.ASCII.GetBytes(publicKey));
                PgpPublicKeyRingBundle pgpRing       = new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(keyFile));
                PgpPublicKey           key           = pgpRing.GetPublicKey(onePassSignature.KeyId);
                Stream                 outStream     = new MemoryStream();

                onePassSignature.InitVerify(key);

                int ch;
                while ((ch = literalStream.ReadByte()) >= 0)
                {
                    onePassSignature.Update((byte)ch);
                    outStream.WriteByte((byte)ch);
                }
                var hashStream = new MemoryStream(Encoding.ASCII.GetBytes(hash));
                outStream.Seek(0, SeekOrigin.Begin);
                if (hashStream.Length != outStream.Length)
                {
                    return(false);
                }
                int left, right;
                while ((left = hashStream.ReadByte()) >= 0 && (right = outStream.ReadByte()) >= 0)
                {
                    if (left != right)
                    {
                        return(false);
                    }
                }
                outStream.Dispose();

                PgpSignatureList signatureList2 = (PgpSignatureList)pgpObjectFactory.NextPgpObject();
                PgpSignature     firstSig       = signatureList2[0];
                if (onePassSignature.Verify(firstSig))
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            } catch {
                return(false);
            }
        }
Exemplo n.º 18
0
        public static PgpObject SkipSignatureList(PgpObjectFactory compressedFactory)
        {
            var message = compressedFactory.NextPgpObject();

            while (message is PgpOnePassSignatureList || message is PgpSignatureList)
            {
                message = compressedFactory.NextPgpObject();
            }
            return(message);
        }
Exemplo n.º 19
0
        private PgpObject GetClearCompressedMessage(PgpPublicKeyEncryptedData publicKeyED, ChoPGPEncryptionKeys encryptionKeys)
        {
            PgpObjectFactory clearFactory = GetClearDataStream(encryptionKeys.PrivateKey, publicKeyED);
            PgpObject        message      = clearFactory.NextPgpObject();

            if (message is PgpOnePassSignatureList)
            {
                message = clearFactory.NextPgpObject();
            }
            return(message);
        }
Exemplo n.º 20
0
        public String DecryptMessage(String encryptedMessage, char[] passPhrase)
        {
            // Remove the Base64 encoding
            byte[] rawMessage = Convert.FromBase64String(encryptedMessage);

            Stream inputStream = new MemoryStream(rawMessage);

            inputStream = PgpUtilities.GetDecoderStream(inputStream);

            PgpObjectFactory     pgpF = new PgpObjectFactory(inputStream);
            PgpEncryptedDataList enc  = null;
            PgpObject            o    = pgpF.NextPgpObject();

            //
            // the first object might be a PGP marker packet.
            //
            if (o is PgpEncryptedDataList)
            {
                enc = (PgpEncryptedDataList)o;
            }
            else
            {
                enc = (PgpEncryptedDataList)pgpF.NextPgpObject();
            }

            PgpPbeEncryptedData pbe = (PgpPbeEncryptedData)enc[0];

            Stream clear = pbe.GetDataStream(passPhrase);

            PgpObjectFactory pgpFact = new PgpObjectFactory(clear);

            PgpLiteralData ld = (PgpLiteralData)pgpFact.NextPgpObject();

            Stream unc = ld.GetInputStream();

            String message;

            using (StreamReader reader = new StreamReader(unc, Encoding.UTF8))
            {
                message = reader.ReadToEnd();
            }

            // Finally verify the integrity
            if (pbe.IsIntegrityProtected())
            {
                if (!pbe.Verify())
                {
                    throw new MessageVerificationException("Failed to verify the message. It might have been modified in transit.");
                }
            }

            return(message);
        }
Exemplo n.º 21
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");
            }
        }
Exemplo n.º 22
0
        private void doTestMissingSubpackets(byte[] signature)
        {
            PgpObjectFactory f   = new PgpObjectFactory(signature);
            object           obj = f.NextPgpObject();

            while (!(obj is PgpSignatureList))
            {
                obj = f.NextPgpObject();
                if (obj is PgpLiteralData)
                {
                    Stream input = ((PgpLiteralData)obj).GetDataStream();
                    Streams.Drain(input);
                }
            }

            PgpSignature sig = ((PgpSignatureList)obj)[0];

            if (sig.Version > 3)
            {
                PgpSignatureSubpacketVector v = sig.GetHashedSubPackets();

                if (v.GetKeyExpirationTime() != 0)
                {
                    Fail("key expiration time not zero for missing subpackets");
                }

                if (!sig.HasSubpackets)
                {
                    Fail("HasSubpackets property was false with packets");
                }
            }
            else
            {
                if (sig.GetHashedSubPackets() != null)
                {
                    Fail("hashed sub packets found when none expected");
                }

                if (sig.GetUnhashedSubPackets() != null)
                {
                    Fail("unhashed sub packets found when none expected");
                }

                if (sig.HasSubpackets)
                {
                    Fail("HasSubpackets property was true with no packets");
                }
            }
        }
Exemplo n.º 23
0
    // Note: I was able to extract the private key into xml format .Net expecs with this
    public static string GetPrivateKeyXml(string inputData)
    {
        Stream           inputStream = IoHelper.GetStream(inputData);
        PgpObjectFactory pgpFactory  = new PgpObjectFactory(PgpUtilities.GetDecoderStream(inputStream));
        PgpObject        pgp         = null;

        if (pgpFactory != null)
        {
            pgp = pgpFactory.NextPgpObject();
        }

        PgpEncryptedDataList encryptedData = null;

        if (pgp is PgpEncryptedDataList)
        {
            encryptedData = (PgpEncryptedDataList)pgp;
        }
        else
        {
            encryptedData = (PgpEncryptedDataList)pgpFactory.NextPgpObject();
        }

        Stream privateKeyStream = File.OpenRead(PrivateKeyOnlyPath);

        // find secret key
        PgpSecretKeyRingBundle pgpKeyRing = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(privateKeyStream));
        PgpPrivateKey          privateKey = null;

        foreach (PgpPublicKeyEncryptedData pked in encryptedData.GetEncryptedDataObjects())
        {
            privateKey = FindSecretKey(pgpKeyRing, pked.KeyId, Password.ToCharArray());
            if (privateKey != null)
            {
                //pubKeyData = pked;
                break;
            }
        }

        // get xml:
        RsaPrivateCrtKeyParameters rpckp = ((RsaPrivateCrtKeyParameters)privateKey.Key);
        RSAParameters dotNetParams       = DotNetUtilities.ToRSAParameters(rpckp);
        RSA           rsa = RSA.Create();

        rsa.ImportParameters(dotNetParams);
        string xmlPrivate = rsa.ToXmlString(true);

        return(xmlPrivate);
    }
Exemplo n.º 24
0
 private static void Decrypt(PgpCompressedData objCompressed, Stream outputStream)
 {
     using (var compressedStream = objCompressed.GetDataStream())
     {
         var factory = new PgpObjectFactory(compressedStream);
         var obj     = factory.NextPgpObject();
         if (obj is PgpOnePassSignatureList)
         {
             Decrypt((PgpLiteralData)factory.NextPgpObject(), outputStream);
         }
         else
         {
             Decrypt((PgpLiteralData)obj, outputStream);
         }
     }
 }
        /**
         * verify the signature in in against the file fileName.
         */
        private static bool VerifySignature(
            string OriginalMessage,
            string EncodedMessage,
            Stream keyIn)
        {
            byte[] bytes = Convert.FromBase64String(EncodedMessage);
            using (Stream inputStream = new MemoryStream(bytes))
            {
                PgpObjectFactory pgpFact = new PgpObjectFactory(PgpUtilities.GetDecoderStream(inputStream));
                PgpSignatureList p3      = null;
                PgpObject        o       = pgpFact.NextPgpObject();
                if (o is PgpCompressedData)
                {
                    PgpCompressedData c1 = (PgpCompressedData)o;
                    pgpFact = new PgpObjectFactory(c1.GetDataStream());

                    p3 = (PgpSignatureList)pgpFact.NextPgpObject();
                }
                else
                {
                    p3 = (PgpSignatureList)o;
                }

                PgpPublicKeyRingBundle pgpPubRingCollection = new PgpPublicKeyRingBundle(
                    PgpUtilities.GetDecoderStream(keyIn));
                PgpSignature sig = p3[0];
                PgpPublicKey key = pgpPubRingCollection.GetPublicKey(sig.KeyId);
                sig.InitVerify(key);
                sig.Update(System.Text.Encoding.UTF8.GetBytes(OriginalMessage));

                return(sig.Verify());
            }
        }
Exemplo n.º 26
0
		/**
        * decrypt the passed in message stream
        */
        private byte[] DecryptMessage(
            byte[] message)
        {
            PgpObjectFactory		pgpF = new PgpObjectFactory(message);
            PgpEncryptedDataList	enc = (PgpEncryptedDataList) pgpF.NextPgpObject();
            PgpPbeEncryptedData		pbe = (PgpPbeEncryptedData) enc[0];
            Stream					clear = pbe.GetDataStream(pass);

			PgpObjectFactory		pgpFact = new PgpObjectFactory(clear);
            PgpCompressedData		cData = (PgpCompressedData) pgpFact.NextPgpObject();
            pgpFact = new PgpObjectFactory(cData.GetDataStream());

			PgpLiteralData ld = (PgpLiteralData) pgpFact.NextPgpObject();

            if (!ld.FileName.Equals("test.txt")
                && !ld.FileName.Equals("_CONSOLE"))
            {
                Fail("wrong filename in packet");
            }

			if (!ld.ModificationTime.Equals(TestDateTime))
			{
				Fail("wrong modification time in packet: " + ld.ModificationTime + " vs " + TestDateTime);
			}

			Stream unc = ld.GetInputStream();
			byte[] bytes = Streams.ReadAll(unc);

			if (pbe.IsIntegrityProtected() && !pbe.Verify())
			{
				Fail("integrity check failed");
			}

			return bytes;
        }
Exemplo n.º 27
0
        /// <summary>
        /// Verify signature
        /// </summary>
        /// <param name="data">Data to verify</param>
        /// <returns>Return true if signature validates, else false.</returns>
        public bool Verify(byte[] data)
        {
            Context = new CryptoContext(Context);

            using (var dataIn = new MemoryStream(data))
                using (var armoredIn = new ArmoredInputStream(dataIn))
                {
                    if (!armoredIn.IsClearText())
                    {
                        var factory = new PgpObjectFactory(armoredIn);

                        DecryptHandlePgpObject(factory.NextPgpObject());
                        if (Context.FailedIntegrityCheck)
                        {
                            throw new VerifyException("Error, failed validation check.");
                        }

                        if (!Context.IsSigned)
                        {
                            throw new CryptoException("Error, message is not signed.");
                        }

                        return(Context.SignatureValidated);
                    }
                }

            return(VerifyClear(data));
        }
Exemplo n.º 28
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");
            }
        }
        private PgpObject getClearCompressedMessage(PgpPublicKeyEncryptedData publicKeyED)
        {
            PgpObjectFactory clearFactory = getClearDataStream(mEncryptionKeys.PrivateKey, publicKeyED);
            PgpObject        message      = clearFactory.NextPgpObject();

            return(message);
        }
Exemplo n.º 30
0
        public static bool VerifySignature(byte[] data, string signature, PgpPublicKey publicKey = null)
        {
            PgpSignatureList p3 = null;

            using (var inputStream = PgpUtilities.GetDecoderStream(Tools.GenerateStreamFromString(signature))) {
                var pgpFact = new PgpObjectFactory(inputStream);
                var o       = pgpFact.NextPgpObject();
                if (o is PgpCompressedData c1)
                {
                    pgpFact = new PgpObjectFactory(c1.GetDataStream());
                    p3      = (PgpSignatureList)pgpFact.NextPgpObject();
                }
                else
                {
                    p3 = (PgpSignatureList)o;
                }
            }

            var sig = p3[0];

            if (publicKey == null)
            {
                publicKey = masterSecretKey.PublicKey;
            }
            sig.InitVerify(publicKey);
            sig.Update(data);

            return(sig.Verify());
        }
Exemplo n.º 31
0
        /// <summary>
        /// Attempt to verify a PGP signed message using the matching public key.
        /// </summary>
        /// <param name="signedMessageStream">Stream containing the signed message.</param>
        /// <param name="signatureStream">Stream containing the signature.</param>
        /// <param name="publicKey">BouncyCastle public key to be used for verification.</param>
        /// <remarks>The message and signature should be passed in without ASCII Armor.</remarks>
        /// <returns>Whether the message's signature is verified.</returns>
        public static bool VerifySignature(Stream signedMessageStream, Stream signatureStream, PgpPublicKey publicKey)
        {
            // Decode from Base-64.
            using (Stream decoderStream = PgpUtilities.GetDecoderStream(signatureStream))
            {
                // Extract the signature list.
                PgpObjectFactory pgpObjectFactory = new PgpObjectFactory(decoderStream);

                PgpObject pgpObject = pgpObjectFactory.NextPgpObject();
                if (pgpObject is PgpSignatureList)
                {
                    PgpSignatureList signatureList = pgpObject as PgpSignatureList;

                    // Hydrate the signature object with the message to be verified.
                    PgpSignature signature = signatureList[0];
                    signature.InitVerify(publicKey);
                    signedMessageStream.Seek(0, SeekOrigin.Begin);
                    for (int i = 0; i < signedMessageStream.Length; i++)
                    {
                        signature.Update((byte)signedMessageStream.ReadByte());
                    }

                    // Return the result.
                    return(signature.Verify());
                }
                else
                {
                    return(false);
                }
            }
        }
Exemplo n.º 32
0
        private void TestDecrypt(PgpSecretKeyRing secretKeyRing)
        {
            PgpObjectFactory pgpF = new PgpObjectFactory(testMessage);

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

            PgpPublicKeyEncryptedData encP = (PgpPublicKeyEncryptedData)encList[0];

            PgpSecretKey secretKey = secretKeyRing.GetSecretKey(); // secretKeyRing.GetSecretKey(encP.KeyId);

            //        PgpPrivateKey pgpPrivKey = secretKey.extractPrivateKey(new JcePBESecretKeyEncryptorBuilder());

            //        clear = encP.getDataStream(pgpPrivKey, "BC");
            //
            //        bOut.reset();
            //
            //        while ((ch = clear.read()) >= 0)
            //        {
            //            bOut.write(ch);
            //        }
            //
            //        out = bOut.toByteArray();
            //
            //        if (!AreEqual(out, text))
            //        {
            //            fail("wrong plain text in Generated packet");
            //        }
        }
Exemplo n.º 33
0
        private void ReadBackTest(
            PgpLiteralDataGenerator generator)
        {
            Random rand = new Random();
            byte[] buf = new byte[MAX];

            rand.NextBytes(buf);

            for (int i = 1; i != MAX; i++)
            {
                MemoryStream bOut = new MemoryStream();

                Stream outputStream = generator.Open(
					new UncloseableStream(bOut),
					PgpLiteralData.Binary,
					PgpLiteralData.Console,
					i,
					DateTime.UtcNow);

				outputStream.Write(buf, 0, i);

                generator.Close();

                PgpObjectFactory fact = new PgpObjectFactory(bOut.ToArray());

                PgpLiteralData data = (PgpLiteralData)fact.NextPgpObject();

                Stream inputStream = data.GetInputStream();

                for (int count = 0; count != i; count++)
                {
                    if (inputStream.ReadByte() != (buf[count] & 0xff))
                    {
                        Fail("failed readback test - length = " + i);
                    }
                }
            }
        }
Exemplo n.º 34
0
        private void PerformTestSig(
            HashAlgorithmTag	hashAlgorithm,
            PgpPublicKey		pubKey,
            PgpPrivateKey		privKey)
        {
            const string data = "hello world!";
            byte[] dataBytes = Encoding.ASCII.GetBytes(data);

            MemoryStream bOut = new UncloseableMemoryStream();
            MemoryStream testIn = new MemoryStream(dataBytes, false);
            PgpSignatureGenerator sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.RsaGeneral, hashAlgorithm);

            sGen.InitSign(PgpSignature.BinaryDocument, privKey);

            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)
            int ch;
            while ((ch = testIn.ReadByte()) >= 0)
            {
                lOut.WriteByte((byte)ch);
                sGen.Update((byte)ch);
            }

            lOut.Close();

            sGen.Generate().Encode(bcOut);

            bcOut.Close();

            //
            // verify generated signature
            //
            PgpObjectFactory pgpFact = new PgpObjectFactory(bOut.ToArray());

            PgpCompressedData c1 = (PgpCompressedData)pgpFact.NextPgpObject();

            pgpFact = new PgpObjectFactory(c1.GetDataStream());

            PgpOnePassSignatureList p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject();

            PgpOnePassSignature ops = p1[0];

            PgpLiteralData p2 = (PgpLiteralData)pgpFact.NextPgpObject();
            if (!p2.ModificationTime.Equals(testDateTime))
            {
                Fail("Modification time not preserved");
            }

            Stream dIn = p2.GetInputStream();

            ops.InitVerify(pubKey);

            // TODO Need a stream object to automatically call Update?
            // (via ISigner implementation of PgpSignatureGenerator)
            while ((ch = dIn.ReadByte()) >= 0)
            {
                ops.Update((byte)ch);
            }

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

            if (!ops.Verify(p3[0]))
            {
                Fail("Failed generated signature check - " + hashAlgorithm);
            }
        }
Exemplo n.º 35
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");
            }
        }
Exemplo n.º 36
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");
            }
        }
        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;
        }
Exemplo n.º 38
0
		private void ValidateData(
			byte[] compressed)
		{
			PgpObjectFactory pgpFact = new PgpObjectFactory(compressed);
			PgpCompressedData c1 = (PgpCompressedData) pgpFact.NextPgpObject();

			Stream pIn = c1.GetDataStream();
			byte[] bytes = Streams.ReadAll(pIn);
			pIn.Close();

			if (!AreEqual(bytes, Data))
			{
				Fail("compression test failed");
			}
		}
Exemplo n.º 39
0
		public override void PerformTest()
		{
			//
			// test immediate close
			//
			MemoryStream bOut = new MemoryStream();
			ArmoredOutputStream aOut = new ArmoredOutputStream(bOut);

			aOut.Close();

			byte[] data = bOut.ToArray();

			if (data.Length != 0)
			{
				Fail("No data should have been written");
			}

			//
			// multiple close
			//
			bOut = new MemoryStream();
			aOut = new ArmoredOutputStream(bOut);

			aOut.Write(sample, 0, sample.Length);

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

			int mc = markerCount(bOut.ToArray());

			if (mc < 1)
			{
				Fail("No end marker found");
			}

			if (mc > 1)
			{
				Fail("More than one end marker found");
			}

			//
			// writing and reading single objects
			//
			bOut = new MemoryStream();
			aOut = new ArmoredOutputStream(bOut);

			aOut.Write(sample, 0, sample.Length);

			aOut.Close();

			ArmoredInputStream aIn = new ArmoredInputStream(
				new MemoryStream(bOut.ToArray(), false));

			PgpObjectFactory fact = new PgpObjectFactory(aIn);
			int count = 0;

			while (fact.NextPgpObject() != null)
			{
				count++;
			}

			if (count != 1)
			{
				Fail("wrong number of objects found: " + count);
			}

			//
			// writing and reading multiple objects  - in single block
			//
			bOut = new MemoryStream();
			aOut = new ArmoredOutputStream(bOut);

			aOut.Write(sample, 0, sample.Length);
			aOut.Write(sample, 0, sample.Length);

			aOut.Close();

			aIn = new ArmoredInputStream(
				new MemoryStream(bOut.ToArray(), false));

			fact = new PgpObjectFactory(aIn);
			count = 0;

			while (fact.NextPgpObject() != null)
			{
				count++;
			}

			if (count != 2)
			{
				Fail("wrong number of objects found: " + count);
			}

			//
			// writing and reading multiple objects  - in single block
			//
			bOut = new MemoryStream();
			aOut = new ArmoredOutputStream(bOut);

			aOut.Write(sample, 0, sample.Length);

			aOut.Close();     // does not close underlying stream

			aOut = new ArmoredOutputStream(bOut);

			aOut.Write(sample, 0, sample.Length);

			aOut.Close();

			aIn = new ArmoredInputStream(
				new MemoryStream(bOut.ToArray(), false));

			count = 0;
			bool atLeastOne;
			do
			{
				atLeastOne = false;
				fact = new PgpObjectFactory(aIn);

				while (fact.NextPgpObject() != null)
				{
					atLeastOne = true;
					count++;
				}
			}
			while (atLeastOne);

			if (count != 2)
			{
				Fail("wrong number of objects found: " + count);
			}

			blankLineTest();
		}
Exemplo n.º 40
0
		public override void PerformTest()
		{
			PgpPublicKey pubKey = null;

			//
			// Read the public key
			//
			PgpObjectFactory pgpFact = new PgpObjectFactory(testPubKeyRing);
			PgpPublicKeyRing pgpPub = (PgpPublicKeyRing)pgpFact.NextPgpObject();

			pubKey = pgpPub.GetPublicKey();

			if (pubKey.BitStrength != 1024)
			{
				Fail("failed - key strength reported incorrectly.");
			}

			//
			// Read the private key
			//
			PgpSecretKeyRing	sKey = new PgpSecretKeyRing(testPrivKeyRing);
			PgpSecretKey		secretKey = sKey.GetSecretKey();
			PgpPrivateKey		pgpPrivKey = secretKey.ExtractPrivateKey(pass);

			//
			// signature generation
			//
			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.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);

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

			lGen.Close();

			sGen.Generate().Encode(bcOut);

			cGen.Close();

			//
			// verify Generated signature
			//
			pgpFact = new PgpObjectFactory(bOut.ToArray());

			PgpCompressedData c1 = (PgpCompressedData)pgpFact.NextPgpObject();

			pgpFact = new PgpObjectFactory(c1.GetDataStream());

			PgpOnePassSignatureList p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject();

			PgpOnePassSignature ops = p1[0];

			PgpLiteralData p2 = (PgpLiteralData)pgpFact.NextPgpObject();
			if (!p2.ModificationTime.Equals(testDateTime))
			{
				Fail("Modification time not preserved");
			}

			Stream    dIn = p2.GetInputStream();

			ops.InitVerify(pubKey);

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

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

			if (!ops.Verify(p3[0]))
			{
				Fail("Failed Generated signature check");
			}

			//
			// test encryption
			//

			//
			// find a key sutiable for encryption
			//
			long pgpKeyID = 0;
			AsymmetricKeyParameter pKey = null;

			foreach (PgpPublicKey pgpKey in pgpPub.GetPublicKeys())
			{
				if (pgpKey.Algorithm == PublicKeyAlgorithmTag.ElGamalEncrypt
					|| pgpKey.Algorithm == PublicKeyAlgorithmTag.ElGamalGeneral)
				{
					pKey = pgpKey.GetKey();
					pgpKeyID = pgpKey.KeyId;
					if (pgpKey.BitStrength != 1024)
					{
						Fail("failed - key strength reported incorrectly.");
					}

					//
					// verify the key
					//

				}
			}

			IBufferedCipher c = CipherUtilities.GetCipher("ElGamal/None/PKCS1Padding");

			c.Init(true, pKey);

			byte[] inBytes = Encoding.ASCII.GetBytes("hello world");
			byte[] outBytes = c.DoFinal(inBytes);

			pgpPrivKey = sKey.GetSecretKey(pgpKeyID).ExtractPrivateKey(pass);

			c.Init(false, pgpPrivKey.Key);

			outBytes = c.DoFinal(outBytes);

			if (!Arrays.AreEqual(inBytes, outBytes))
			{
				Fail("decryption failed.");
			}

			//
			// encrypted message
			//
			byte[] text = { (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o',
								(byte)' ', (byte)'w', (byte)'o', (byte)'r', (byte)'l', (byte)'d', (byte)'!', (byte)'\n' };

			PgpObjectFactory pgpF = new PgpObjectFactory(encMessage);

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

			PgpPublicKeyEncryptedData encP = (PgpPublicKeyEncryptedData)encList[0];

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

			//
			// signed and encrypted message
			//
			pgpF = new PgpObjectFactory(signedAndEncMessage);

			encList = (PgpEncryptedDataList)pgpF.NextPgpObject();

			encP = (PgpPublicKeyEncryptedData)encList[0];

			clear = encP.GetDataStream(pgpPrivKey);

			pgpFact = new PgpObjectFactory(clear);

			c1 = (PgpCompressedData)pgpFact.NextPgpObject();

			pgpFact = new PgpObjectFactory(c1.GetDataStream());

			p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject();

			ops = p1[0];

			ld = (PgpLiteralData)pgpFact.NextPgpObject();

			bOut = new MemoryStream();

			if (!ld.FileName.Equals("test.txt"))
			{
				throw new Exception("wrong filename in packet");
			}

			inLd = ld.GetDataStream();

			//
			// note: we use the DSA public key here.
			//
			ops.InitVerify(pgpPub.GetPublicKey());

			while ((ch = inLd.ReadByte()) >= 0)
			{
				ops.Update((byte) ch);
				bOut.WriteByte((byte) ch);
			}

			p3 = (PgpSignatureList)pgpFact.NextPgpObject();

			if (!ops.Verify(p3[0]))
			{
				Fail("Failed signature check");
			}

			if (!Arrays.AreEqual(bOut.ToArray(), text))
			{
				Fail("wrong plain text in decrypted packet");
			}

			//
			// encrypt
			//
			MemoryStream cbOut = new MemoryStream();
			PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator(
				SymmetricKeyAlgorithmTag.TripleDes, random);
			PgpPublicKey puK = sKey.GetSecretKey(pgpKeyID).PublicKey;

			cPk.AddMethod(puK);

			Stream cOut = cPk.Open(new UncloseableStream(cbOut), bOut.ToArray().Length);

			cOut.Write(text, 0, text.Length);

			cOut.Close();

			pgpF = new PgpObjectFactory(cbOut.ToArray());

			encList = (PgpEncryptedDataList)pgpF.NextPgpObject();

			encP = (PgpPublicKeyEncryptedData)encList[0];

			pgpPrivKey = sKey.GetSecretKey(pgpKeyID).ExtractPrivateKey(pass);

			clear = encP.GetDataStream(pgpPrivKey);
			outBytes = Streams.ReadAll(clear);

			if (!Arrays.AreEqual(outBytes, text))
			{
				Fail("wrong plain text in Generated packet");
			}

			//
			// use of PgpKeyPair
			//
			BigInteger g = new BigInteger("153d5d6172adb43045b68ae8e1de1070b6137005686d29d3d73a7749199681ee5b212c9b96bfdcfa5b20cd5e3fd2044895d609cf9b410b7a0f12ca1cb9a428cc", 16);
			BigInteger p = new BigInteger("9494fec095f3b85ee286542b3836fc81a5dd0a0349b4c239dd38744d488cf8e31db8bcb7d33b41abb9e5a33cca9144b1cef332c94bf0573bf047a3aca98cdf3b", 16);

			ElGamalParameters elParams = new ElGamalParameters(p, g);

			IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator("ELGAMAL");
			kpg.Init(new ElGamalKeyGenerationParameters(random, elParams));

			AsymmetricCipherKeyPair kp = kpg.GenerateKeyPair();

			PgpKeyPair pgpKp = new PgpKeyPair(PublicKeyAlgorithmTag.ElGamalGeneral ,
				kp.Public, kp.Private, DateTime.UtcNow);

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





			// Test bug with ElGamal P size != 0 mod 8 (don't use these sizes at home!)
			for (int pSize = 257; pSize < 264; ++pSize)
			{
				// Generate some parameters of the given size
				ElGamalParametersGenerator epg = new ElGamalParametersGenerator();
				epg.Init(pSize, 2, random);

				elParams = epg.GenerateParameters();

				kpg = GeneratorUtilities.GetKeyPairGenerator("ELGAMAL");
				kpg.Init(new ElGamalKeyGenerationParameters(random, elParams));


				// Run a short encrypt/decrypt test with random key for the given parameters
				kp = kpg.GenerateKeyPair();

				PgpKeyPair elGamalKeyPair = new PgpKeyPair(
					PublicKeyAlgorithmTag.ElGamalGeneral, kp, DateTime.UtcNow);

				cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, random);

				puK = elGamalKeyPair.PublicKey;

				cPk.AddMethod(puK);

				cbOut = new MemoryStream();

				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 = elGamalKeyPair.PrivateKey;

				// Note: This is where an exception would be expected if the P size causes problems
				clear = encP.GetDataStream(pgpPrivKey);
				byte[] decText = Streams.ReadAll(clear);

				if (!Arrays.AreEqual(text, decText))
				{
					Fail("decrypted message incorrect");
				}
			}


			// check sub key encoding

			foreach (PgpPublicKey pgpKey in pgpPub.GetPublicKeys())
			{
				if (!pgpKey.IsMasterKey)
				{
					byte[] kEnc = pgpKey.GetEncoded();

					PgpObjectFactory objF = new PgpObjectFactory(kEnc);

					// TODO Make PgpPublicKey a PgpObject or return a PgpPublicKeyRing
//					PgpPublicKey k = (PgpPublicKey)objF.NextPgpObject();
//
//					pKey = k.GetKey();
//					pgpKeyID = k.KeyId;
//					if (k.BitStrength != 1024)
//					{
//						Fail("failed - key strength reported incorrectly.");
//					}
//
//					if (objF.NextPgpObject() != null)
//					{
//						Fail("failed - stream not fully parsed.");
//					}
                }
            }
		}
Exemplo n.º 41
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();
        }
        private void verifySignature(
			byte[] encodedSig,
			HashAlgorithmTag hashAlgorithm,
			IPgpPublicKey pubKey,
			byte[] original)
        {
            PgpObjectFactory        pgpFact = new PgpObjectFactory(encodedSig);
            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();
            PgpSignature sig = p3[0];

            DateTime creationTime = sig.CreationTime;

            // Check creationTime is recent
            if (creationTime.CompareTo(DateTime.UtcNow) > 0
                || creationTime.CompareTo(DateTime.UtcNow.AddMinutes(-10)) < 0)
            {
                Fail("bad creation time in signature: " + creationTime);
            }

            if (sig.KeyId != pubKey.KeyId)
            {
                Fail("key id mismatch in signature");
            }

            if (!ops.Verify(sig))
            {
                Fail("Failed generated signature check - " + hashAlgorithm);
            }

            sig.InitVerify(pubKey);

            for (int i = 0; i != original.Length; i++)
            {
                sig.Update(original[i]);
            }

            sig.Update(original);

            if (!sig.Verify())
            {
                Fail("Failed generated signature check against original data");
            }
        }
Exemplo n.º 43
0
		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]));
		}
Exemplo n.º 44
0
		private byte[] DecryptMessageBuffered(
			byte[] message)
		{
			PgpObjectFactory		pgpF = new PgpObjectFactory(message);
			PgpEncryptedDataList	enc = (PgpEncryptedDataList) pgpF.NextPgpObject();
			PgpPbeEncryptedData		pbe = (PgpPbeEncryptedData) enc[0];

			Stream clear = pbe.GetDataStream(pass);

			PgpObjectFactory	pgpFact = new PgpObjectFactory(clear);
			PgpCompressedData	cData = (PgpCompressedData) pgpFact.NextPgpObject();

			pgpFact = new PgpObjectFactory(cData.GetDataStream());

			PgpLiteralData ld = (PgpLiteralData) pgpFact.NextPgpObject();

			MemoryStream bOut = new MemoryStream();
			if (!ld.FileName.Equals("test.txt")
				&& !ld.FileName.Equals("_CONSOLE"))
			{
				Fail("wrong filename in packet");
			}
			if (!ld.ModificationTime.Equals(TestDateTime))
			{
				Fail("wrong modification time in packet: " + ld.ModificationTime.Ticks + " " + TestDateTime.Ticks);
			}

			Stream unc = ld.GetInputStream();
			byte[] buf = new byte[1024];

			int len;
			while ((len = unc.Read(buf, 0, buf.Length)) > 0)
			{
				bOut.Write(buf, 0, len);
			}

			if (pbe.IsIntegrityProtected() && !pbe.Verify())
			{
				Fail("integrity check failed");
			}

			return bOut.ToArray();
		}
        /**
        * Generated signature test
        *
        * @param sKey
        * @param pgpPrivKey
        * @return test result
        */
        public void GenerateTest(
            PgpSecretKeyRing sKey,
            IPgpPublicKey     pgpPubKey,
            IPgpPrivateKey    pgpPrivKey)
        {
            string data = "hello world!";
            MemoryStream bOut = new MemoryStream();

            byte[] dataBytes = Encoding.ASCII.GetBytes(data);
            MemoryStream testIn = new MemoryStream(dataBytes, false);

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

            sGen.InitSign(PgpSignature.BinaryDocument, pgpPrivKey);

            PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator();

            IEnumerator enumerator = sKey.GetSecretKey().PublicKey.GetUserIds().GetEnumerator();
            enumerator.MoveNext();
            string primaryUserId = (string) enumerator.Current;

            spGen.SetSignerUserId(true, primaryUserId);

            sGen.SetHashedSubpackets(spGen.Generate());

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

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

            lGen.Close();

            sGen.Generate().Encode(bcOut);

            cGen.Close();

            PgpObjectFactory pgpFact = new PgpObjectFactory(bOut.ToArray());
            PgpCompressedData c1 = (PgpCompressedData)pgpFact.NextPgpObject();

            pgpFact = new PgpObjectFactory(c1.GetDataStream());

            PgpOnePassSignatureList p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject();
            PgpOnePassSignature ops = p1[0];

            PgpLiteralData p2 = (PgpLiteralData) pgpFact.NextPgpObject();
            if (!p2.ModificationTime.Equals(testDateTime))
            {
                Fail("Modification time not preserved");
            }

            Stream dIn = p2.GetInputStream();

            ops.InitVerify(pgpPubKey);

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

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

            if (!ops.Verify(p3[0]))
            {
                Fail("Failed generated signature check");
            }
        }
		private void messageTest(
			string message,
			string type)
		{
			ArmoredInputStream aIn = new ArmoredInputStream(
				new MemoryStream(Encoding.ASCII.GetBytes(message)));

			string[] headers = aIn.GetArmorHeaders();

			if (headers == null || headers.Length != 1)
			{
				Fail("wrong number of headers found");
			}

			if (!"Hash: SHA256".Equals(headers[0]))
			{
				Fail("header value wrong: " + headers[0]);
			}

			//
			// read the input, making sure we ingore the last newline.
			//
			MemoryStream bOut = new MemoryStream();
			int ch;

			while ((ch = aIn.ReadByte()) >= 0 && aIn.IsClearText())
			{
				bOut.WriteByte((byte)ch);
			}

			PgpPublicKeyRingBundle pgpRings = new PgpPublicKeyRingBundle(publicKey);

			PgpObjectFactory	pgpFact = new PgpObjectFactory(aIn);
			PgpSignatureList	p3 = (PgpSignatureList)pgpFact.NextPgpObject();
			PgpSignature		sig = p3[0];

			sig.InitVerify(pgpRings.GetPublicKey(sig.KeyId));

			MemoryStream lineOut = new MemoryStream();
			Stream sigIn = new MemoryStream(bOut.ToArray(), false);
			int lookAhead = ReadInputLine(lineOut, sigIn);

			ProcessLine(sig, lineOut.ToArray());

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

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

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

			if (!sig.Verify())
			{
				Fail("signature failed to verify m_in " + type);
			}
		}
Exemplo n.º 47
0
		private void doSigGenerateTest(
			string				privateKeyFile,
			string				publicKeyFile,
			HashAlgorithmTag	digest)
		{
			PgpSecretKeyRing		secRing = loadSecretKey(privateKeyFile);
			PgpPublicKeyRing		pubRing = loadPublicKey(publicKeyFile);
			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, digest);

			sGen.InitSign(PgpSignature.BinaryDocument, secRing.GetSecretKey().ExtractPrivateKey("test".ToCharArray()));

			BcpgOutputStream bcOut = new BcpgOutputStream(bOut);

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

			PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator();

//			Date testDate = new Date((System.currentTimeMillis() / 1000) * 1000);
			DateTime testDate = new DateTime(
				(DateTime.UtcNow.Ticks / TimeSpan.TicksPerSecond) * TimeSpan.TicksPerSecond);

			Stream lOut = lGen.Open(
				new UncloseableStream(bcOut),
				PgpLiteralData.Binary,
				"_CONSOLE",
				dataBytes.Length,
				testDate);

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

			lGen.Close();

			sGen.Generate().Encode(bcOut);

			PgpObjectFactory        pgpFact = new PgpObjectFactory(bOut.ToArray());
			PgpOnePassSignatureList p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject();
			PgpOnePassSignature     ops = p1[0];

			Assert.AreEqual(digest, ops.HashAlgorithm);
			Assert.AreEqual(PublicKeyAlgorithmTag.Dsa, ops.KeyAlgorithm);

			PgpLiteralData          p2 = (PgpLiteralData)pgpFact.NextPgpObject();
			if (!p2.ModificationTime.Equals(testDate))
			{
				Assert.Fail("Modification time not preserved");
			}

			Stream dIn = p2.GetInputStream();

			ops.InitVerify(pubRing.GetPublicKey());

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

			PgpSignatureList p3 = (PgpSignatureList)pgpFact.NextPgpObject();
			PgpSignature sig = p3[0];

			Assert.AreEqual(digest, sig.HashAlgorithm);
			Assert.AreEqual(PublicKeyAlgorithmTag.Dsa, sig.KeyAlgorithm);

			Assert.IsTrue(ops.Verify(sig));
		}
Exemplo n.º 48
0
        private void TestDecrypt(PgpSecretKeyRing secretKeyRing)
        {
            PgpObjectFactory pgpF = new PgpObjectFactory(testMessage);

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

            PgpPublicKeyEncryptedData encP = (PgpPublicKeyEncryptedData)encList[0];

            PgpSecretKey secretKey = secretKeyRing.GetSecretKey(); // secretKeyRing.GetSecretKey(encP.KeyId);

    //        PgpPrivateKey pgpPrivKey = secretKey.extractPrivateKey(new JcePBESecretKeyEncryptorBuilder());

    //        clear = encP.getDataStream(pgpPrivKey, "BC");
    //
    //        bOut.reset();
    //
    //        while ((ch = clear.read()) >= 0)
    //        {
    //            bOut.write(ch);
    //        }
    //
    //        out = bOut.toByteArray();
    //
    //        if (!AreEqual(out, text))
    //        {
    //            fail("wrong plain text in Generated packet");
    //        }
        }
Exemplo n.º 49
0
		public override void PerformTest()
        {
            byte[] data = DecryptMessage(enc1);
            if (data[0] != 'h' || data[1] != 'e' || data[2] != 'l')
            {
                Fail("wrong plain text in packet");
            }

			//
            // create a PBE encrypted message and read it back.
            //
			byte[] text = Encoding.ASCII.GetBytes("hello world!\n");

			//
            // encryption step - convert to literal data, compress, encode.
            //
            MemoryStream bOut = new UncloseableMemoryStream();

            PgpCompressedDataGenerator comData = new PgpCompressedDataGenerator(
                CompressionAlgorithmTag.Zip);

            PgpLiteralDataGenerator lData = new PgpLiteralDataGenerator();
			Stream comOut = comData.Open(new UncloseableStream(bOut));
            Stream ldOut = lData.Open(
				new UncloseableStream(comOut),
                PgpLiteralData.Binary,
                PgpLiteralData.Console,
                text.Length,
                TestDateTime);

			ldOut.Write(text, 0, text.Length);
			ldOut.Close();

			comOut.Close();

			//
            // encrypt - with stream close
            //
            MemoryStream cbOut = new UncloseableMemoryStream();
            PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator(
				SymmetricKeyAlgorithmTag.Cast5, new SecureRandom());

            cPk.AddMethod(pass, HashAlgorithmTag.Sha1);

			byte[] bOutData = bOut.ToArray();
			Stream cOut = cPk.Open(new UncloseableStream(cbOut), bOutData.Length);
            cOut.Write(bOutData, 0, bOutData.Length);
            cOut.Close();

			data = DecryptMessage(cbOut.ToArray());
            if (!Arrays.AreEqual(data, text))
            {
                Fail("wrong plain text in generated packet");
            }

			//
			// encrypt - with generator close
			//
			cbOut = new UncloseableMemoryStream();
			cPk = new PgpEncryptedDataGenerator(
				SymmetricKeyAlgorithmTag.Cast5, new SecureRandom());

            cPk.AddMethod(pass, HashAlgorithmTag.Sha1);

			bOutData = bOut.ToArray();
			cOut = cPk.Open(new UncloseableStream(cbOut), bOutData.Length);
			cOut.Write(bOutData, 0, bOutData.Length);

			cPk.Close();

			data = DecryptMessage(cbOut.ToArray());

			if (!AreEqual(data, text))
			{
				Fail("wrong plain text in generated packet");
			}

			//
            // encrypt - partial packet style.
            //
            SecureRandom rand = new SecureRandom();
            byte[] test = new byte[1233];

            rand.NextBytes(test);

			bOut = new UncloseableMemoryStream();

			comData = new PgpCompressedDataGenerator(
				CompressionAlgorithmTag.Zip);
			comOut = comData.Open(new UncloseableStream(bOut));

			lData = new PgpLiteralDataGenerator();
            ldOut = lData.Open(
				new UncloseableStream(comOut),
                PgpLiteralData.Binary,
                PgpLiteralData.Console,
                TestDateTime,
                new byte[16]);

            ldOut.Write(test, 0, test.Length);
            lData.Close();

			comData.Close();
            cbOut = new UncloseableMemoryStream();
            cPk = new PgpEncryptedDataGenerator(
				SymmetricKeyAlgorithmTag.Cast5, rand);

            cPk.AddMethod(pass, HashAlgorithmTag.Sha1);

			cOut = cPk.Open(new UncloseableStream(cbOut), new byte[16]);
            {
                byte[] tmp = bOut.ToArray();
                cOut.Write(tmp, 0, tmp.Length);
            }

			cPk.Close();

			data = DecryptMessage(cbOut.ToArray());
            if (!Arrays.AreEqual(data, test))
            {
                Fail("wrong plain text in generated packet");
            }

            //
            // with integrity packet
            //
            cbOut = new UncloseableMemoryStream();
            cPk = new PgpEncryptedDataGenerator(
				SymmetricKeyAlgorithmTag.Cast5, true, rand);

            cPk.AddMethod(pass, HashAlgorithmTag.Sha1);

            cOut = cPk.Open(new UncloseableStream(cbOut), new byte[16]);
            bOutData = bOut.ToArray();
            cOut.Write(bOutData, 0, bOutData.Length);
            cPk.Close();

			data = DecryptMessage(cbOut.ToArray());
            if (!Arrays.AreEqual(data, test))
            {
                Fail("wrong plain text in generated packet");
            }

			//
			// decrypt with buffering
			//
			data = DecryptMessageBuffered(cbOut.ToArray());
			if (!AreEqual(data, test))
			{
				Fail("wrong plain text in buffer generated packet");
			}

			//
			// sample message
			//
			PgpObjectFactory pgpFact = new PgpObjectFactory(testPBEAsym);

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

			PgpPbeEncryptedData pbe = (PgpPbeEncryptedData) enc[1];

			Stream clear = pbe.GetDataStream("password".ToCharArray());

			pgpFact = new PgpObjectFactory(clear);

			PgpLiteralData ld = (PgpLiteralData) pgpFact.NextPgpObject();

			Stream unc = ld.GetInputStream();
			byte[] bytes = Streams.ReadAll(unc);

			if (!AreEqual(bytes, Hex.Decode("5361742031302e30322e30370d0a")))
			{
				Fail("data mismatch on combined PBE");
			}

			//
			// with integrity packet - one byte message
			//
			byte[] msg = new byte[1];
			bOut = new MemoryStream();

			comData = new PgpCompressedDataGenerator(
				CompressionAlgorithmTag.Zip);

			lData = new PgpLiteralDataGenerator();
			comOut = comData.Open(new UncloseableStream(bOut));
			ldOut = lData.Open(
				new UncloseableStream(comOut),
				PgpLiteralData.Binary,
				PgpLiteralData.Console,
				msg.Length,
				TestDateTime);

			ldOut.Write(msg, 0, msg.Length);

			ldOut.Close();

			comOut.Close();
        
			cbOut = new MemoryStream();
			cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, true, rand);

            cPk.AddMethod(pass, HashAlgorithmTag.Sha1);

			cOut = cPk.Open(new UncloseableStream(cbOut), new byte[16]);

			data = bOut.ToArray();
			cOut.Write(data, 0, data.Length);

			cOut.Close();

			data = DecryptMessage(cbOut.ToArray());
			if (!AreEqual(data, msg))
			{
				Fail("wrong plain text in generated packet");
			}

			//
			// decrypt with buffering
			//
			data = DecryptMessageBuffered(cbOut.ToArray());
			if (!AreEqual(data, msg))
			{
				Fail("wrong plain text in buffer generated packet");
			}
		}
        private void doTestMissingSubpackets(byte[] signature)
        {
            PgpObjectFactory f = new PgpObjectFactory(signature);
            object obj = f.NextPgpObject();

            while (!(obj is PgpSignatureList))
            {
                obj = f.NextPgpObject();
                if (obj is PgpLiteralData)
                {
                    Stream input = ((PgpLiteralData)obj).GetDataStream();
                    Streams.Drain(input);
                }
            }

            PgpSignature sig = ((PgpSignatureList)obj)[0];

            if (sig.Version > 3)
            {
                var v = sig.GetHashedSubPackets();

                if (v.GetKeyExpirationTime() != 0)
                {
                    Fail("key expiration time not zero for missing subpackets");
                }

                if (!sig.HasSubpackets)
                {
                    Fail("HasSubpackets property was false with packets");
                }
            }
            else
            {
                if (sig.GetHashedSubPackets() != null)
                {
                    Fail("hashed sub packets found when none expected");
                }

                if (sig.GetUnhashedSubPackets() != null)
                {
                    Fail("unhashed sub packets found when none expected");
                }

                if (sig.HasSubpackets)
                {
                    Fail("HasSubpackets property was true with no packets");
                }
            }
        }
Exemplo n.º 51
0
        private void EncryptDecryptTest()
        {
            SecureRandom random = SecureRandom.GetInstance("SHA1PRNG");

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

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

            AsymmetricCipherKeyPair kpEnc = keyGen.GenerateKeyPair();

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

            PgpLiteralDataGenerator lData = new PgpLiteralDataGenerator();
            MemoryStream ldOut = new MemoryStream();
            Stream pOut = lData.Open(ldOut, PgpLiteralDataGenerator.Utf8, PgpLiteralData.Console, text.Length, DateTime.UtcNow);

            pOut.Write(text, 0, text.Length);

            pOut.Close();

            byte[] data = ldOut.ToArray();

            MemoryStream cbOut = new MemoryStream();

            PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, random);
            cPk.AddMethod(ecdhKeyPair.PublicKey);

            Stream cOut = cPk.Open(new UncloseableStream(cbOut), data.Length);

            cOut.Write(data, 0, data.Length);

            cOut.Close();

            PgpObjectFactory pgpF = new PgpObjectFactory(cbOut.ToArray());

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

            PgpPublicKeyEncryptedData encP = (PgpPublicKeyEncryptedData)encList[0];

            Stream clear = encP.GetDataStream(ecdhKeyPair.PrivateKey);

            pgpF = new PgpObjectFactory(clear);

            PgpLiteralData ld = (PgpLiteralData)pgpF.NextPgpObject();

            clear = ld.GetInputStream();
            MemoryStream bOut = new MemoryStream();

            int ch;
            while ((ch = clear.ReadByte()) >= 0)
            {
                bOut.WriteByte((byte)ch);
            }

            byte[] output = bOut.ToArray();

            if (!AreEqual(output, text))
            {
                Fail("wrong plain text in Generated packet");
            }
        }
        public override void PerformTest()
        {
            //
            // RSA tests
            //
            PgpSecretKeyRing pgpPriv = new PgpSecretKeyRing(rsaKeyRing);
            IPgpSecretKey secretKey = pgpPriv.GetSecretKey();
            IPgpPrivateKey pgpPrivKey = secretKey.ExtractPrivateKey(rsaPass);

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

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

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

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

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

            sGen.InitSign(PgpSignature.KeyRevocation, pgpPrivKey);

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

            sig.InitVerify(secretKey.PublicKey);

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

            PgpSecretKeyRing pgpDSAPriv = new PgpSecretKeyRing(dsaKeyRing);
            IPgpSecretKey secretDSAKey = pgpDSAPriv.GetSecretKey();
            IPgpPrivateKey pgpPrivDSAKey = secretDSAKey.ExtractPrivateKey(dsaPass);

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

            sGen.InitSign(PgpSignature.SubkeyBinding, pgpPrivDSAKey);

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

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

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

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

            byte[] sigBytes = sig.GetEncoded();

            PgpObjectFactory f = new PgpObjectFactory(sigBytes);

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

            sig.InitVerify(secretDSAKey.PublicKey);

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

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

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

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

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

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

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

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

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

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

            SignatureSubpacketTag[] criticalHashed = hashedPcks.GetCriticalTags();

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

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

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

            sGen.InitSign(PgpSignature.SubkeyBinding, pgpPrivDSAKey);

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

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

            sig.InitVerify(secretDSAKey.PublicKey);

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

            hashedPcks = sig.GetHashedSubPackets();

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

            unhashedPcks = sig.GetUnhashedSubPackets();

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

            try
            {
                sig.VerifyCertification(secretKey.PublicKey);

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

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

            sGen.InitSign(PgpSignature.SubkeyBinding, pgpPrivDSAKey);

            hashedGen = new PgpSignatureSubpacketGenerator();

            DateTime creationTime = new DateTime(1973, 7, 27);
            hashedGen.SetSignatureCreationTime(false, creationTime);

            sGen.SetHashedSubpackets(hashedGen.Generate());

            sGen.SetUnhashedSubpackets(null);

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

            sig.InitVerify(secretDSAKey.PublicKey);

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

            hashedPcks = sig.GetHashedSubPackets();

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

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

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

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

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

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

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

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

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

            criticalHashed = hashedPcks.GetCriticalTags();

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

            unhashedPcks = sig.GetUnhashedSubPackets();

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

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

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

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

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

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

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

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

            // special cases
            //
            doTestMissingSubpackets(nullPacketsSubKeyBinding);

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

            // keyflags
            doTestKeyFlagsValues();
        }
Exemplo n.º 53
0
        private void MixedTest(
            PgpPrivateKey	pgpPrivKey,
            PgpPublicKey	pgpPubKey)
        {
            byte[] text = Encoding.ASCII.GetBytes("hello world!\n");

            //
            // literal data
            //
            MemoryStream bOut = new MemoryStream();
            PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator();
            Stream lOut = lGen.Open(
                bOut,
                PgpLiteralData.Binary,
                PgpLiteralData.Console,
                text.Length,
                DateTime.UtcNow);

            lOut.Write(text, 0, text.Length);

            lGen.Close();

            byte[] bytes = bOut.ToArray();

            PgpObjectFactory f = new PgpObjectFactory(bytes);
            CheckLiteralData((PgpLiteralData)f.NextPgpObject(), text);

            MemoryStream bcOut = new MemoryStream();

            PgpEncryptedDataGenerator encGen = new PgpEncryptedDataGenerator(
                SymmetricKeyAlgorithmTag.Aes128,
                true,
                new SecureRandom());

            encGen.AddMethod(pgpPubKey);

            encGen.AddMethod("password".ToCharArray(), HashAlgorithmTag.Sha1);

            Stream cOut = encGen.Open(bcOut, bytes.Length);

            cOut.Write(bytes, 0, bytes.Length);

            cOut.Close();

            byte[] encData = bcOut.ToArray();

            //
            // asymmetric
            //
            PgpObjectFactory pgpF = new PgpObjectFactory(encData);

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

            PgpPublicKeyEncryptedData  encP = (PgpPublicKeyEncryptedData)encList[0];

            Stream clear = encP.GetDataStream(pgpPrivKey);

            PgpObjectFactory pgpFact = new PgpObjectFactory(clear);

            CheckLiteralData((PgpLiteralData)pgpFact.NextPgpObject(), text);

            //
            // PBE
            //
            pgpF = new PgpObjectFactory(encData);

            encList = (PgpEncryptedDataList)pgpF.NextPgpObject();

            PgpPbeEncryptedData encPbe = (PgpPbeEncryptedData) encList[1];

            clear = encPbe.GetDataStream("password".ToCharArray());

            pgpF = new PgpObjectFactory(clear);

            CheckLiteralData((PgpLiteralData) pgpF.NextPgpObject(), text);
        }