예제 #1
0
        private void DoTestMasterKey()
        {
            PgpSecretKey key = PgpSecretKey.ParseSecretKeyFromSExpr(new MemoryStream(sExprKeyMaster, false),
                "test".ToCharArray());

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

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

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

            if (!sig.Verify())
            {
                Fail("signature failed to verify!");
            }
        }
예제 #2
0
        private static void WriteOutputAndSign(Stream compressedOut, Stream literalOut, FileStream inputFile, PgpSignatureGenerator signatureGenerator)
        {
            int length = 0;

            byte[] buf = new byte[BufferSize];
            while ((length = inputFile.Read(buf, 0, buf.Length)) > 0)
            {
                literalOut.Write(buf, 0, length);
                signatureGenerator.Update(buf, 0, length);
            }
            signatureGenerator.Generate().Encode(compressedOut);
        }
예제 #3
0
        /// <summary>
        /// Signs then encrypts data using key and list of recipients.
        /// </summary>
        /// <param name="data">Data to encrypt</param>
        /// <param name="key">Signing key</param>
        /// <param name="recipients">List of keys to encrypt to</param>
        /// <returns>Returns ascii armored signed/encrypted data</returns>
        protected string SignAndEncrypt(byte[] data, string key, IList <string> recipients, Dictionary <string, string> headers, bool isBinary)
        {
            Context = new CryptoContext(Context);

            var senderKey = GetSecretKeyForEncryption(key);

            if (senderKey == null)
            {
                throw new SecretKeyNotFoundException("Error, Unable to locate sender encryption key \"" + key + "\".");
            }

            var senderSignKey = GetSecretKeyForSigning(key);

            if (senderSignKey == null)
            {
                throw new SecretKeyNotFoundException("Error, Unable to locate sender signing key \"" + key + "\".");
            }

            var compressedData = new PgpCompressedDataGenerator(CompressionAlgorithmTag.ZLib);
            var literalData    = new PgpLiteralDataGenerator();
            var cryptData      = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, true, new SecureRandom());

            foreach (var recipient in recipients)
            {
                var recipientKey = GetPublicKeyForEncryption(recipient);
                if (recipientKey == null)
                {
                    throw new PublicKeyNotFoundException("Error, unable to find recipient key \"" + recipient + "\".");
                }

                cryptData.AddMethod(recipientKey);
            }

            // Setup signature stuff //
            var signatureData = new PgpSignatureGenerator(
                senderSignKey.PublicKey.Algorithm,
                HashAlgorithmTag.Sha256);

            signatureData.InitSign(
                isBinary ? PgpSignature.BinaryDocument : PgpSignature.CanonicalTextDocument,
                senderSignKey.ExtractPrivateKey(Context.Password));

            foreach (string userId in senderKey.PublicKey.GetUserIds())
            {
                var subPacketGenerator = new PgpSignatureSubpacketGenerator();

                subPacketGenerator.SetSignerUserId(false, userId);
                signatureData.SetHashedSubpackets(subPacketGenerator.Generate());

                // Just the first one!
                break;
            }
            // //

            using (var sout = new MemoryStream())
            {
                using (var armoredOut = new ArmoredOutputStream(sout))
                {
                    foreach (var header in headers)
                    {
                        armoredOut.SetHeader(header.Key, header.Value);
                    }

                    using (var clearOut = new MemoryStream())
                    {
                        using (var compressedOut = compressedData.Open(clearOut))
                        {
                            signatureData.GenerateOnePassVersion(false).Encode(compressedOut);

                            using (var literalOut = literalData.Open(
                                       compressedOut,
                                       isBinary ? PgpLiteralData.Binary : PgpLiteralData.Text,
                                       "",
                                       data.Length,
                                       DateTime.UtcNow))
                            {
                                literalOut.Write(data, 0, data.Length);
                                signatureData.Update(data, 0, data.Length);
                            }

                            signatureData.Generate().Encode(compressedOut);
                        }

                        var clearData = clearOut.ToArray();

                        using (var encryptOut = cryptData.Open(armoredOut, clearData.Length))
                        {
                            encryptOut.Write(clearData, 0, clearData.Length);
                        }
                    }
                }

                return(ASCIIEncoding.ASCII.GetString(sout.ToArray()));
            }
        }
        /**
         * Generate an encapsulated signed file.
         *
         * @param fileName
         * @param keyIn
         * @param outputStream
         * @param pass
         * @param armor
         */
        private static void SignFile(
            string fileName,
            Stream keyIn,
            Stream outputStream,
            char[]      pass,
            bool armor,
            bool compress)
        {
            if (armor)
            {
                outputStream = new ArmoredOutputStream(outputStream);
            }

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

            sGen.InitSign(PgpSignature.BinaryDocument, pgpPrivKey);
            foreach (string userId in pgpSec.PublicKey.GetUserIds())
            {
                PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator();
                spGen.SetSignerUserId(false, userId);
                sGen.SetHashedSubpackets(spGen.Generate());
                // Just the first one!
                break;
            }

            Stream cOut = outputStream;
            PgpCompressedDataGenerator cGen = null;

            if (compress)
            {
                cGen = new PgpCompressedDataGenerator(CompressionAlgorithmTag.ZLib);

                cOut = cGen.Open(cOut);
            }

            BcpgOutputStream bOut = new BcpgOutputStream(cOut);

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

            FileInfo file = new FileInfo(fileName);
            PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator();
            Stream     lOut = lGen.Open(bOut, PgpLiteralData.Binary, file);
            FileStream fIn  = file.OpenRead();
            int        ch   = 0;

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

            fIn.Close();
            lGen.Close();

            sGen.Generate().Encode(bOut);

            if (cGen != null)
            {
                cGen.Close();
            }

            if (armor)
            {
                outputStream.Close();
            }
        }
예제 #5
0
        public override void PerformTest()
        {
            //
            // Read the public key
            //
            PgpPublicKeyRing pubKeyRing = new PgpPublicKeyRing(testPubKey);
            foreach (PgpSignature certification in pubKeyRing.GetPublicKey().GetSignatures())
            {
                certification.InitVerify(pubKeyRing.GetPublicKey());

                if (!certification.VerifyCertification((string)First(pubKeyRing.GetPublicKey().GetUserIds()), pubKeyRing.GetPublicKey()))
                {
                    Fail("self certification does not verify");
                }
            }

            if (pubKeyRing.GetPublicKey().BitStrength != 256)
            {
                Fail("incorrect bit strength returned");
            }

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

            PgpPrivateKey privKey = secretKeyRing.GetSecretKey().ExtractPrivateKey(testPasswd);

            GenerateAndSign();

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

            PgpSecretKey key = PgpSecretKey.ParseSecretKeyFromSExpr(new MemoryStream(sExprKey, false), "test".ToCharArray());

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

            PgpSignature sig = signGen.Generate();
            sig.InitVerify(key.PublicKey);
            sig.Update(msg);

            if (!sig.Verify())
            {
                Fail("signature failed to verify!");
            }
        }
예제 #6
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="SecretKey"></param>
        /// <param name="Passhrase"></param>
        /// <param name="Reason"></param>
        /// <param name="RevokeDescription"></param>
        /// <param name="OutFile"></param>
        public static void GenerateCertificate(PgpSecretKey SecretKey, char[] Passhrase, string Reason, string RevokeDescription, string OutFile)
        {
            RevocationReasonTag RevokeReason;

            if (string.Equals(Reason, "Compromised", StringComparison.CurrentCultureIgnoreCase))
            {
                RevokeReason = RevocationReasonTag.KeyCompromised;
            }
            else if (string.Equals(Reason, "Retired", StringComparison.CurrentCultureIgnoreCase))
            {
                RevokeReason = RevocationReasonTag.KeyRetired;
            }
            else if (string.Equals(Reason, "Superseded", StringComparison.CurrentCultureIgnoreCase))
            {
                RevokeReason = RevocationReasonTag.KeySuperseded;
            }
            else if (string.Equals(Reason, "NoReason", StringComparison.CurrentCultureIgnoreCase))
            {
                RevokeReason = RevocationReasonTag.NoReason;
            }
            else if (string.Equals(Reason, "Invalid", StringComparison.CurrentCultureIgnoreCase))
            {
                RevokeReason = RevocationReasonTag.UserNoLongerValid;
            }
            else
            {
                RevokeReason = RevocationReasonTag.NoReason;
            }

            // Create the subpacket generators for the hashed and unhashed packets.
            var subHashGenerator   = new PgpSignatureSubpacketGenerator();
            var subUnHashGenerator = new PgpSignatureSubpacketGenerator();

            // Extract the private key from the secret key.
            PgpPrivateKey privKey;

            try
            {
                privKey = SecretKey.ExtractPrivateKey(Passhrase);
            }
            catch
            {
                throw new PgpException("Wrong Passphrase, could not extract private key.");
            }

            // Create a signature generator and initialize it for key revocation.
            var generator = new PgpSignatureGenerator(SecretKey.PublicKey.Algorithm, HashAlgorithmTag.Sha256);

            generator.InitSign(PgpSignature.KeyRevocation, privKey, new SecureRandom());

            // Create the hashed and unhashed subpackets and add them to the signature generator.
            subHashGenerator.SetSignatureCreationTime(false, DateTime.UtcNow);
            subHashGenerator.SetRevocationReason(false, RevokeReason, RevokeDescription);
            subUnHashGenerator.SetRevocationKey(false, SecretKey.PublicKey.Algorithm, SecretKey.PublicKey.GetFingerprint());
            generator.SetHashedSubpackets(subHashGenerator.Generate());
            generator.SetUnhashedSubpackets(subUnHashGenerator.Generate());

            // Generate the certification
            var signature = generator.GenerateCertification(SecretKey.PublicKey);

            // Create the armour output stream and set the headers
            var mStream = new MemoryStream();

            using (var outAStream = new ArmoredOutputStream(mStream))
            {
                outAStream.SetHeader("Version", "Posh-OpenPGP");
                outAStream.SetHeader("Comment", "A revocation certificate should follow");
                signature.Encode(outAStream);
                outAStream.Close();
            }

            // Turn the stream in to armour text and make sure we replace the propper headers
            mStream.Position = 0;
            var sr     = new StreamReader(mStream);
            var armour = sr.ReadToEnd();
            var outstr = armour.Replace("BEGIN PGP SIGNATURE", "BEGIN PGP PUBLIC KEY BLOCK").Replace("END PGP SIGNATURE", "END PGP PUBLIC KEY BLOCK");

            // Save the string to the specified file.
            System.IO.File.WriteAllText(OutFile, outstr);
        }
예제 #7
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.");
//					}
                }
            }
		}
예제 #8
0
        /*
         * 文章 -> hash -> 私鑰(自己)簽章 -> 簽章後的hash值
         * 文章 - - - - - - - - - - - - - -> 文章
         */


        /*.......................................................................數位簽章開始*/


        private static void SignFile(
            string fileName,     //預計數位簽章原始檔案的完整路徑
            Stream keyIn,        // Private key 的 File Stream (自己)
            Stream outputStream, //預計匯出(數位簽章後) File Stream
            char[] pass,         // private Key 的 password
            bool armor,          //盔甲??? 範例預設true
            bool compress        //解壓縮 範例預設true
            )
        {
            if (armor)
            {
                outputStream = new ArmoredOutputStream(outputStream);            //匯出位置、headers、雜湊表
            }
            PgpSecretKey  pgpSec     = PgpExampleUtilities.ReadSecretKey(keyIn); //PgpSecretKey包含私鑰及公鑰整個物件
            PgpPrivateKey pgpPrivKey = pgpSec.ExtractPrivateKey(pass);           //需輸入私鑰密碼才能取出私鑰

            /*
             * SHA是由美國國家安全局制定,主要應用於數字簽名標準裡面的數字簽名算法( DSA : Digital Signature Algorithm ),
             * SHA家族中以SHA1和SHA256最為廣泛使用。SHA1的雜湊值長度為160bit、SHA256則為256bit,長度越長碰撞的機會就越低也越安全,
             * 但同時計算的時間複雜度也隨著增高。
             */

            PgpSignatureGenerator sGen = new PgpSignatureGenerator(pgpSec.PublicKey.Algorithm, HashAlgorithmTag.Sha256); //PublicKey.Algorithm即原始公鑰

            sGen.InitSign(PgpSignature.BinaryDocument, pgpPrivKey);                                                      //若沒私鑰重新生產一個

            foreach (string userId in pgpSec.PublicKey.GetUserIds())                                                     //ExportKeyPair 的 identity (MarkWu)
            {
                PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator();
                spGen.SetSignerUserId(false, userId);       //數位簽章的使用者
                sGen.SetHashedSubpackets(spGen.Generate()); //將 SignatureSubpacket 陣列化再回傳
                // Just the first one!
                break;
            }
            Stream cOut = outputStream;
            PgpCompressedDataGenerator cGen = null;

            if (compress) //解壓縮
            {
                cGen = new PgpCompressedDataGenerator(CompressionAlgorithmTag.ZLib);
                cOut = cGen.Open(cOut);
            }
            BcpgOutputStream bOut = new BcpgOutputStream(cOut);

            sGen.GenerateOnePassVersion(false).Encode(bOut);  //hash 加密

            FileInfo file = new FileInfo(fileName);
            PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator();
            Stream     lOut = lGen.Open(bOut, PgpLiteralData.Binary, file);
            FileStream fIn  = file.OpenRead();
            int        ch   = 0;

            while ((ch = fIn.ReadByte()) >= 0) //從資料流讀取一個位元組
            {
                lOut.WriteByte((byte)ch);      //寫入預計匯出檔案
                sGen.Update((byte)ch);         //進行加密?
            }
            fIn.Close();
            lGen.Close();
            sGen.Generate().Encode(bOut);
            if (cGen != null)
            {
                cGen.Close();
            }
            if (armor)
            {
                outputStream.Close();
            }
        }
예제 #9
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));
		}
예제 #10
0
        /// <summary>
        /// Create a file with PGP clear text signature. See documentation at https://github.com/CommunityHiQ/Frends.Community.PgpClearTextSignature Returns: Object {string FilePath}
        /// </summary>
        public static PgpClearTextSignatureResult ClearTextSignFile(PgpClearTextSignatureInput input)
        {
            HashAlgorithmTag digest;

            switch (input.HashFunction)
            {
            case PgpClearTextSignatureHashFunctionType.Md5:
                digest = HashAlgorithmTag.MD5;
                break;

            case PgpClearTextSignatureHashFunctionType.RipeMd160:
                digest = HashAlgorithmTag.RipeMD160;
                break;

            case PgpClearTextSignatureHashFunctionType.Sha1:
                digest = HashAlgorithmTag.Sha1;
                break;

            case PgpClearTextSignatureHashFunctionType.Sha224:
                digest = HashAlgorithmTag.Sha224;
                break;

            case PgpClearTextSignatureHashFunctionType.Sha384:
                digest = HashAlgorithmTag.Sha384;
                break;

            case PgpClearTextSignatureHashFunctionType.Sha512:
                digest = HashAlgorithmTag.Sha512;
                break;

            case PgpClearTextSignatureHashFunctionType.Sha256:
                digest = HashAlgorithmTag.Sha256;
                break;

            default:
                digest = HashAlgorithmTag.Sha256;
                break;
            }

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

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

            sGen.InitSign(PgpSignature.CanonicalTextDocument, pgpPrivKey);

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

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

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

            var aOut = new ArmoredOutputStream(outputStream);

            aOut.BeginClearText(digest);

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

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

            while (lookAhead != -1)
            {
                lookAhead = PgpServices.ReadInputLine(lineOut, lookAhead, fIn);

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

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

            fIn.Close();

            aOut.EndClearText();

            var bOut = new BcpgOutputStream(aOut);

            sGen.Generate().Encode(bOut);

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

            var ret = new PgpClearTextSignatureResult
            {
                FilePath = input.OutputFile
            };

            return(ret);
        }
예제 #11
0
        public static void CreateSignature(
            string fileName,
            PgpSecretKey keyIn,
            Stream outputStream,
            char[] pass,
            bool armor,
            string digestName)
        {
            if (armor)
            {
                outputStream = new ArmoredOutputStream(outputStream);
            }

            HashAlgorithmTag digest;

            if (string.Equals(digestName, "Sha256", StringComparison.CurrentCultureIgnoreCase))
            {
                digest = HashAlgorithmTag.Sha256;
            }
            else if (string.Equals(digestName, "Sha384", StringComparison.CurrentCultureIgnoreCase))
            {
                digest = HashAlgorithmTag.Sha384;
            }
            else if (string.Equals(digestName, "Sha512", StringComparison.CurrentCultureIgnoreCase))
            {
                digest = HashAlgorithmTag.Sha512;
            }
            else if (string.Equals(digestName, "MD5", StringComparison.CurrentCultureIgnoreCase))
            {
                digest = HashAlgorithmTag.MD5;
            }
            else if (string.Equals(digestName, "RipeMD160", StringComparison.CurrentCultureIgnoreCase))
            {
                digest = HashAlgorithmTag.RipeMD160;
            }
            else
            {
                digest = HashAlgorithmTag.Sha512;
            }

            var pgpPrivKey = keyIn.ExtractPrivateKey(pass);
            var sGen       = new PgpSignatureGenerator(
                keyIn.PublicKey.Algorithm, digest);

            sGen.InitSign(PgpSignature.BinaryDocument, pgpPrivKey);

            var bOut = new BcpgOutputStream(outputStream);

            Stream fIn = File.OpenRead(fileName);

            int ch;

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

            fIn.Close();

            sGen.Generate().Encode(bOut);

            if (armor)
            {
                outputStream.Close();
            }
        }
예제 #12
0
        private static void OutputSign(Stream compressedO, Stream literalO, FileStream iFile, PgpSignatureGenerator sigGen)
        {
            int length = 0;

            byte[] buf = new byte[BufferSize];
            while ((length = iFile.Read(buf, 0, buf.Length)) > 0)
            {
                literalO.Write(buf, 0, length);
                sigGen.Update(buf, 0, length);
            }
            sigGen.Generate().Encode(compressedO);
        }
        private static byte[] SignPublicKey(
			IPgpSecretKey	secretKey,
			string			secretKeyPass,
			IPgpPublicKey	keyToBeSigned,
			string			notationName,
			string			notationValue,
			bool			armor)
        {
            Stream os = new MemoryStream();
            if (armor)
            {
                os = new ArmoredOutputStream(os);
            }

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

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

            sGen.InitSign(PgpSignature.DirectKey, pgpPrivKey);

            BcpgOutputStream bOut = new BcpgOutputStream(os);

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

            PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator();

            bool isHumanReadable = true;

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

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

            bOut.Flush();

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

            return PgpPublicKey.AddCertification(keyToBeSigned, sGen.Generate()).GetEncoded();
        }
예제 #14
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="SecretKey"></param>
        /// <param name="Passhrase"></param>
        /// <param name="Reason"></param>
        /// <param name="RevokeDescription"></param>
        /// <returns></returns>
        public static PgpSignature GenerateSignature(PgpSecretKey SecretKey, char[] Passhrase, string Reason, string RevokeDescription)
        {
            RevocationReasonTag RevokeReason;

            if (string.Equals(Reason, "Compromised", StringComparison.CurrentCultureIgnoreCase))
            {
                RevokeReason = RevocationReasonTag.KeyCompromised;
            }
            else if (string.Equals(Reason, "Retired", StringComparison.CurrentCultureIgnoreCase))
            {
                RevokeReason = RevocationReasonTag.KeyRetired;
            }
            else if (string.Equals(Reason, "Superseded", StringComparison.CurrentCultureIgnoreCase))
            {
                RevokeReason = RevocationReasonTag.KeySuperseded;
            }
            else if (string.Equals(Reason, "NoReason", StringComparison.CurrentCultureIgnoreCase))
            {
                RevokeReason = RevocationReasonTag.NoReason;
            }
            else if (string.Equals(Reason, "Invalid", StringComparison.CurrentCultureIgnoreCase))
            {
                RevokeReason = RevocationReasonTag.UserNoLongerValid;
            }
            else
            {
                RevokeReason = RevocationReasonTag.NoReason;
            }

            // Create the subpacket generators for the hashed and unhashed packets.
            var subHashGenerator   = new PgpSignatureSubpacketGenerator();
            var subUnHashGenerator = new PgpSignatureSubpacketGenerator();

            // Extract the private key from the secret key.
            PgpPrivateKey privKey;

            try
            {
                privKey = SecretKey.ExtractPrivateKey(Passhrase);
            }
            catch
            {
                throw new PgpException("Wrong Passphrase, could not extract private key.");
            }

            // Create a signature generator and initialize it for key revocation.
            var generator = new PgpSignatureGenerator(SecretKey.PublicKey.Algorithm, HashAlgorithmTag.Sha256);

            generator.InitSign(PgpSignature.KeyRevocation, privKey, new SecureRandom());

            // Create the hashed and unhashed subpackets and add them to the signature generator.
            subHashGenerator.SetSignatureCreationTime(false, DateTime.UtcNow);
            subHashGenerator.SetRevocationReason(false, RevokeReason, RevokeDescription);
            subUnHashGenerator.SetRevocationKey(false, SecretKey.PublicKey.Algorithm, SecretKey.PublicKey.GetFingerprint());
            generator.SetHashedSubpackets(subHashGenerator.Generate());
            generator.SetUnhashedSubpackets(subUnHashGenerator.Generate());

            // Generate the certification
            var signature = generator.GenerateCertification(SecretKey.PublicKey);

            return(signature);
        }
예제 #15
0
        /**
         * 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");
            }
        }
예제 #16
0
        /// <summary>
        /// Attempt to encrypt a message using PGP with the specified public key(s).
        /// </summary>
        /// <param name="messageStream">Stream containing the message to encrypt.</param>
        /// <param name="fileName">File name of for the message.</param>
        /// <param name="signedAndEncryptedMessageStream">Stream to write the encrypted message into.</param>
        /// <param name="senderPublicKey">The BouncyCastle public key associated with the signature.</param>
        /// <param name="senderPrivateKey">The BouncyCastle private key to be used for signing.</param>
        /// <param name="recipientPublicKeys">Collection of BouncyCastle public keys to be used for encryption.</param>
        /// <param name="hashAlgorithmTag">The hash algorithm tag to use for signing.</param>
        /// <param name="symmetricKeyAlgorithmTag">The symmetric key algorithm tag to use for encryption.</param>
        /// <param name="armor">Whether to wrap the message with ASCII armor.</param>
        /// <returns>Whether the encryption completed successfully.</returns>
        public static bool SignAndEncrypt(Stream messageStream, string fileName, Stream signedAndEncryptedMessageStream, PgpPublicKey senderPublicKey, PgpPrivateKey senderPrivateKey, IEnumerable <PgpPublicKey> recipientPublicKeys, HashAlgorithmTag hashAlgorithmTag = HashAlgorithmTag.Sha256, SymmetricKeyAlgorithmTag symmetricKeyAlgorithmTag = SymmetricKeyAlgorithmTag.TripleDes, bool armor = true)
        {
            // Create a signature generator.
            PgpSignatureGenerator signatureGenerator = new PgpSignatureGenerator(senderPublicKey.Algorithm, hashAlgorithmTag);

            signatureGenerator.InitSign(PgpSignature.BinaryDocument, senderPrivateKey);

            // Add the public key user ID.
            foreach (string userId in senderPublicKey.GetUserIds())
            {
                PgpSignatureSubpacketGenerator signatureSubGenerator = new PgpSignatureSubpacketGenerator();
                signatureSubGenerator.SetSignerUserId(false, userId);
                signatureGenerator.SetHashedSubpackets(signatureSubGenerator.Generate());
                break;
            }

            // Allow any of the corresponding keys to be used for decryption.
            PgpEncryptedDataGenerator encryptedDataGenerator = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.TripleDes, true, new SecureRandom());

            foreach (PgpPublicKey publicKey in recipientPublicKeys)
            {
                encryptedDataGenerator.AddMethod(publicKey);
            }

            // Handle optional ASCII armor.
            if (armor)
            {
                using (Stream armoredStream = new ArmoredOutputStream(signedAndEncryptedMessageStream))
                {
                    using (Stream encryptedStream = encryptedDataGenerator.Open(armoredStream, new byte[Constants.LARGEBUFFERSIZE]))
                    {
                        PgpCompressedDataGenerator compressedDataGenerator = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Uncompressed);
                        using (Stream compressedStream = compressedDataGenerator.Open(encryptedStream))
                        {
                            signatureGenerator.GenerateOnePassVersion(false).Encode(compressedStream);

                            PgpLiteralDataGenerator literalDataGenerator = new PgpLiteralDataGenerator();
                            using (Stream literalStream = literalDataGenerator.Open(compressedStream, PgpLiteralData.Binary,
                                                                                    fileName, DateTime.Now, new byte[Constants.LARGEBUFFERSIZE]))
                            {
                                // Process each character in the message.
                                int messageChar;
                                while ((messageChar = messageStream.ReadByte()) >= 0)
                                {
                                    literalStream.WriteByte((byte)messageChar);
                                    signatureGenerator.Update((byte)messageChar);
                                }
                            }

                            signatureGenerator.Generate().Encode(compressedStream);
                        }
                    }
                }
            }
            else
            {
                using (Stream encryptedStream = encryptedDataGenerator.Open(signedAndEncryptedMessageStream, new byte[Constants.LARGEBUFFERSIZE]))
                {
                    PgpCompressedDataGenerator compressedDataGenerator = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Uncompressed);
                    using (Stream compressedStream = compressedDataGenerator.Open(encryptedStream))
                    {
                        signatureGenerator.GenerateOnePassVersion(false).Encode(compressedStream);

                        PgpLiteralDataGenerator literalDataGenerator = new PgpLiteralDataGenerator();
                        using (Stream literalStream = literalDataGenerator.Open(compressedStream, PgpLiteralData.Binary,
                                                                                fileName, DateTime.Now, new byte[Constants.LARGEBUFFERSIZE]))
                        {
                            // Process each character in the message.
                            int messageChar;
                            while ((messageChar = messageStream.ReadByte()) >= 0)
                            {
                                literalStream.WriteByte((byte)messageChar);
                                signatureGenerator.Update((byte)messageChar);
                            }
                        }

                        signatureGenerator.Generate().Encode(compressedStream);
                    }
                }
            }

            return(true);
        }
        /**
        * 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 static void ProcessLine(
			Stream					aOut,
			PgpSignatureGenerator	sGen,
			byte[]					line)
		{
			int length = GetLengthWithoutWhiteSpace(line);
			if (length > 0)
			{
				sGen.Update(line, 0, length);
			}

			aOut.Write(line, 0, line.Length);
		}
        public override void PerformTest()
        {
            //
            // Read the public key
            //
            PgpPublicKeyRing pgpPub = new PgpPublicKeyRing(testPubKey);

            var pubKey = pgpPub.GetPublicKey();

            //
            // Read the private key
            //
            PgpSecretKeyRing sKey = new PgpSecretKeyRing(testPrivKey);
            IPgpSecretKey secretKey = sKey.GetSecretKey();
            IPgpPrivateKey pgpPrivKey = secretKey.ExtractPrivateKey(pass);

            //
            // test signature message
            //
            PgpObjectFactory pgpFact = new PgpObjectFactory(sig1);
            PgpCompressedData c1 = (PgpCompressedData)pgpFact.NextPgpObject();
            pgpFact = new PgpObjectFactory(c1.GetDataStream());

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

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

            Stream dIn = p2.GetInputStream();

            ops.InitVerify(pubKey);

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

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

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

            //
            // signature generation
            //
            GenerateTest(sKey, pubKey, pgpPrivKey);

            //
            // signature generation - canonical text
            //
            const string data = "hello world!";
            byte[] dataBytes = Encoding.ASCII.GetBytes(data);
            MemoryStream bOut = new MemoryStream();
            MemoryStream testIn = new MemoryStream(dataBytes, false);
            PgpSignatureGenerator sGen = new PgpSignatureGenerator(
                PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1);

            sGen.InitSign(PgpSignature.CanonicalTextDocument, pgpPrivKey);

            PgpCompressedDataGenerator  cGen = new PgpCompressedDataGenerator(
                CompressionAlgorithmTag.Zip);

            BcpgOutputStream bcOut = new BcpgOutputStream(cGen.Open(new UncloseableStream(bOut)));

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

            PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator();
            DateTime testDateTime = new DateTime(1973, 7, 27);
            Stream lOut = lGen.Open(
                new UncloseableStream(bcOut),
                PgpLiteralData.Text,
                "_CONSOLE",
                dataBytes.Length,
                testDateTime);

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

            lGen.Close();

            sGen.Generate().Encode(bcOut);

            cGen.Close();

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

            c1 = (PgpCompressedData) pgpFact.NextPgpObject();

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

            p1 = (PgpOnePassSignatureList) pgpFact.NextPgpObject();

            ops = p1[0];

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

            dIn = p2.GetInputStream();

            ops.InitVerify(pubKey);

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

            p3 = (PgpSignatureList) pgpFact.NextPgpObject();

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

            //
            // Read the public key with user attributes
            //
            pgpPub = new PgpPublicKeyRing(testPubWithUserAttr);

            pubKey = pgpPub.GetPublicKey();

            int count = 0;
            foreach (PgpUserAttributeSubpacketVector attributes in pubKey.GetUserAttributes())
            {
                int sigCount = 0;
                foreach (object sigs in pubKey.GetSignaturesForUserAttribute(attributes))
                {
                    if (sigs == null)
                        Fail("null signature found");

                    sigCount++;
                }

                if (sigCount != 1)
                {
                    Fail("Failed user attributes signature check");
                }

                count++;
            }

            if (count != 1)
            {
                Fail("Failed user attributes check");
            }

            byte[]  pgpPubBytes = pgpPub.GetEncoded();
            pgpPub = new PgpPublicKeyRing(pgpPubBytes);
            pubKey = pgpPub.GetPublicKey();
            count = 0;

            foreach (object ua in pubKey.GetUserAttributes())
            {
                if (ua == null)
                    Fail("null user attribute found");

                count++;
            }

            if (count != 1)
            {
                Fail("Failed user attributes reread");
            }

            //
            // reading test extra data - key with edge condition for DSA key password.
            //
            char[] passPhrase = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };

            sKey = new PgpSecretKeyRing(testPrivKey2);
            pgpPrivKey = sKey.GetSecretKey().ExtractPrivateKey(passPhrase);

            //
            // reading test - aes256 encrypted passphrase.
            //
            sKey = new PgpSecretKeyRing(aesSecretKey);
            pgpPrivKey = sKey.GetSecretKey().ExtractPrivateKey(pass);

            //
            // reading test - twofish encrypted passphrase.
            //
            sKey = new PgpSecretKeyRing(twofishSecretKey);
            pgpPrivKey = sKey.GetSecretKey().ExtractPrivateKey(pass);

            //
            // use of PgpKeyPair
            //
            DsaParametersGenerator pGen = new DsaParametersGenerator();
            pGen.Init(512, 80, new SecureRandom()); // TODO Is the certainty okay?
            DsaParameters dsaParams = pGen.GenerateParameters();
            DsaKeyGenerationParameters kgp = new DsaKeyGenerationParameters(new SecureRandom(), dsaParams);
            IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator("DSA");
            kpg.Init(kgp);

            IAsymmetricCipherKeyPair kp = kpg.GenerateKeyPair();

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

            PgpPublicKey k1 = pgpKp.PublicKey;
            PgpPrivateKey k2 = pgpKp.PrivateKey;
        }
        private void doTestTextSig(
			PublicKeyAlgorithmTag	encAlgorithm,
			HashAlgorithmTag		hashAlgorithm,
			IPgpPublicKey			pubKey,
			IPgpPrivateKey			privKey,
			byte[]					data,
			byte[]					canonicalData)
        {
            PgpSignatureGenerator sGen = new PgpSignatureGenerator(encAlgorithm, HashAlgorithmTag.Sha1);
            MemoryStream bOut = new MemoryStream();
            MemoryStream testIn = new MemoryStream(data, false);
            DateTime creationTime = DateTime.UtcNow;

            sGen.InitSign(PgpSignature.CanonicalTextDocument, privKey);
            sGen.GenerateOnePassVersion(false).Encode(bOut);

            PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator();
            Stream lOut = lGen.Open(
                new UncloseableStream(bOut),
                PgpLiteralData.Text,
                "_CONSOLE",
                data.Length * 2,
                creationTime);

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

            lOut.Write(data, 0, data.Length);
            sGen.Update(data);

            lGen.Close();

            PgpSignature sig = sGen.Generate();

            if (sig.CreationTime == DateTimeUtilities.UnixMsToDateTime(0))
            {
                Fail("creation time not set in v4 signature");
            }

            sig.Encode(bOut);

            verifySignature(bOut.ToArray(), hashAlgorithm, pubKey, canonicalData);
        }
예제 #21
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.");
//					}
                }
            }
        }
        public static string EncryptAndSign(
            Stream messageStream,
            string publicKeyIn,
            string privateKeyIn,
            string passPhrase,
            out Stream outputStream)
        {
            PgpPublicKey  senderPublicKey  = ReadPublicKey(publicKeyIn);
            PgpPrivateKey senderPrivateKey = ReadPrivateKey(privateKeyIn, passPhrase);

            outputStream = new MemoryStream();

            // Create a signature generator.
            PgpSignatureGenerator signatureGenerator = new PgpSignatureGenerator(senderPublicKey.Algorithm, HashAlgorithmTag.Sha256);

            signatureGenerator.InitSign(PgpSignature.BinaryDocument, senderPrivateKey);

            // Add the public key user ID.
            foreach (string userId in senderPublicKey.GetUserIds())
            {
                PgpSignatureSubpacketGenerator signatureSubGenerator = new PgpSignatureSubpacketGenerator();
                signatureSubGenerator.SetSignerUserId(false, userId);
                signatureGenerator.SetHashedSubpackets(signatureSubGenerator.Generate());
                break;
            }

            // Allow any of the corresponding keys to be used for decryption.
            PgpEncryptedDataGenerator encryptedDataGenerator = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.TripleDes, true, new SecureRandom());

            encryptedDataGenerator.AddMethod(senderPublicKey);


            using (Stream armoredStream = new ArmoredOutputStream(outputStream))
            {
                using (Stream encryptedStream = encryptedDataGenerator.Open(armoredStream, new byte[0x10000]))
                {
                    PgpCompressedDataGenerator compressedDataGenerator = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Uncompressed);
                    using (Stream compressedStream = compressedDataGenerator.Open(encryptedStream))
                    {
                        signatureGenerator.GenerateOnePassVersion(false).Encode(compressedStream);

                        PgpLiteralDataGenerator literalDataGenerator = new PgpLiteralDataGenerator();
                        using (Stream literalStream = literalDataGenerator.Open(compressedStream, PgpLiteralData.Binary,
                                                                                PgpLiteralData.Console, DateTime.Now, new byte[0x10000]))
                        {
                            // Process each character in the message.
                            int messageChar;
                            while ((messageChar = messageStream.ReadByte()) >= 0)
                            {
                                literalStream.WriteByte((byte)messageChar);
                                signatureGenerator.Update((byte)messageChar);
                            }
                        }

                        signatureGenerator.Generate().Encode(compressedStream);
                    }
                }
            }

            byte[] signedAndEncryptedMessageBuffer = (outputStream as MemoryStream).ToArray();

            Console.WriteLine(Encoding.ASCII.GetString(signedAndEncryptedMessageBuffer));
            return(Encoding.ASCII.GetString(signedAndEncryptedMessageBuffer));
        }
예제 #23
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);
            }
        }
예제 #24
0
        private void GenerateAndSign()
        {
            SecureRandom random = SecureRandom.GetInstance("SHA1PRNG");

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

            AsymmetricCipherKeyPair kpSign = keyGen.GenerateKeyPair();

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

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

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

            signGen.Update(msg);

            PgpSignature sig = signGen.Generate();

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

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

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

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

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

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


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

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

            if (!sig.Verify())
            {
                Fail("re-encoded signature failed to verify!");
            }
        }
예제 #25
0
        private void EmbeddedJpegTest()
        {
            PgpPublicKeyRing pgpPub = new PgpPublicKeyRing(testPubKey);
            PgpSecretKeyRing pgpSec = new PgpSecretKeyRing(testPrivKey);

            PgpPublicKey pubKey = pgpPub.GetPublicKey();

            PgpUserAttributeSubpacketVectorGenerator vGen = new PgpUserAttributeSubpacketVectorGenerator();

            vGen.SetImageAttribute(ImageAttrib.Format.Jpeg, jpegImage);

            PgpUserAttributeSubpacketVector uVec = vGen.Generate();

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

            sGen.InitSign(PgpSignature.PositiveCertification, pgpSec.GetSecretKey().ExtractPrivateKey(pass));

            PgpSignature sig = sGen.GenerateCertification(uVec, pubKey);

            PgpPublicKey nKey = PgpPublicKey.AddCertification(pubKey, uVec, sig);

            int count = 0;
            foreach (PgpUserAttributeSubpacketVector attributes in nKey.GetUserAttributes())
            {
                int sigCount = 0;
                foreach (PgpSignature s in nKey.GetSignaturesForUserAttribute(attributes))
                {
                    s.InitVerify(pubKey);

                    if (!s.VerifyCertification(attributes, pubKey))
                    {
                        Fail("added signature failed verification");
                    }

                    sigCount++;
                }

                if (sigCount != 1)
                {
                    Fail("Failed added user attributes signature check");
                }
                count++;
            }

            if (count != 1)
            {
                Fail("didn't find added user attributes");
            }

            nKey = PgpPublicKey.RemoveCertification(nKey, uVec);

            if (nKey.GetUserAttributes().GetEnumerator().MoveNext())
            {
                Fail("found attributes where none expected");
            }
        }
예제 #26
0
        /// <summary>
        /// Sign data using key
        /// </summary>
        /// <param name="data">Data to sign</param>
        /// <param name="key">Email address of key</param>
        /// <returns>Returns ascii armored signature</returns>
        public string SignClear(string data, string key, Encoding encoding, Dictionary <string, string> headers)
        {
            Context = new CryptoContext(Context);

            var senderKey = GetSecretKeyForSigning(key);

            if (senderKey == null)
            {
                throw new SecretKeyNotFoundException("Error, unable to locate signing key \"" + key + "\".");
            }

            // Setup signature stuff //
            var signatureData = new PgpSignatureGenerator(senderKey.PublicKey.Algorithm, HashAlgorithmTag.Sha1);

            signatureData.InitSign(PgpSignature.CanonicalTextDocument, senderKey.ExtractPrivateKey(Context.Password));

            foreach (string userId in senderKey.PublicKey.GetUserIds())
            {
                var subPacketGenerator = new PgpSignatureSubpacketGenerator();

                subPacketGenerator.SetSignerUserId(false, userId);
                signatureData.SetHashedSubpackets(subPacketGenerator.Generate());

                // Just the first one!
                break;
            }

            // //

            using (var sout = new MemoryStream())
            {
                using (var armoredOut = new ArmoredOutputStream(sout))
                {
                    foreach (var header in headers)
                    {
                        armoredOut.SetHeader(header.Key, header.Value);
                    }

                    armoredOut.BeginClearText(HashAlgorithmTag.Sha1);

                    // Remove any extra trailing whitespace.
                    // this should not include \r or \n.
                    data = data.TrimEnd(null);

                    using (var stringReader = new StringReader(data))
                    {
                        do
                        {
                            var line = stringReader.ReadLine();
                            if (line == null)
                            {
                                break;
                            }

                            // Lines must have all white space removed
                            line = line.TrimEnd(null);
                            line = line.TrimEnd(new char[] { ' ', '\t', '\r', '\n' });

                            line += "\r\n";

                            signatureData.Update(encoding.GetBytes(line));
                            armoredOut.Write(encoding.GetBytes(line));
                        }while (true);
                    }

                    // Write extra line before signature block.
                    armoredOut.Write(encoding.GetBytes("\r\n"));
                    armoredOut.EndClearText();

                    using (var outputStream = new BcpgOutputStream(armoredOut))
                    {
                        signatureData.Generate().Encode(outputStream);
                    }
                }

                return(encoding.GetString(sout.ToArray()));
            }
        }
예제 #27
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();
        }
예제 #28
0
파일: DSA2Test.cs 프로젝트: 894880010/MP
        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));
        }
예제 #29
0
        public static void AddSignature(PgpPublicKey key, KeyStoreDB keyDb, string keyExportName, PgpSecretKey secKey, char[] passPhrase,
                                        SignatureOperation op, DateTime expiryDate, PgpSignature certLevel = null, string userId = "")
        {
            string fileData = string.Empty;
            bool   useTemp  = true;

            if (key == null)
            {
                throw new ArgumentNullException("key");
            }
            if (keyDb == null)
            {
                throw new ArgumentNullException("keyDb");
            }
            if (!Enum.IsDefined(typeof(SignatureOperation), op))
            {
                throw new ArgumentOutOfRangeException(string.Format("op: {0}", op));
            }

            AlgorithmAgreement algorithms = new AlgorithmAgreement(new List <PgpPublicKey>()
            {
                key
            });
            PgpPrivateKey         privateKey = secKey.ExtractPrivateKey(passPhrase);
            PgpSignatureGenerator sigGen     = new PgpSignatureGenerator(key.Algorithm, algorithms.AgreedHashAlgorithm);

            switch (op)
            {
            case SignatureOperation.AddUserId:
                break;

            case SignatureOperation.RevokeKey:
                MemoryStream mStream = new MemoryStream();
                using (ArmoredOutputStream outArmour = new ArmoredOutputStream(mStream)) {
                    outArmour.SetHeader("Version", "Lynx Privacy");
                    sigGen.InitSign(PgpSignature.KeyRevocation, privateKey);
                    PgpSignature sig = sigGen.GenerateCertification(secKey.PublicKey);
                    PgpPublicKey.AddCertification(secKey.PublicKey, sig);
                    sig.InitVerify(secKey.PublicKey);
                    if (!sig.VerifyCertification(secKey.PublicKey))
                    {
                        throw new PgpException("revocation verification failed.");
                    }
                    sig.Encode(outArmour);
                    outArmour.Close();
                }
                mStream.Position = 0;
                StreamReader srdr   = new StreamReader(mStream);
                string       armour = srdr.ReadToEnd();
                string       outstr = armour.Replace("BEGIN PGP SIGNATURE", "BEGIN PGP PUBLIC KEY BLOCK")
                                      .Replace("END PGP SIGNATURE", "END PGP PUBLIC KEY BLOCK");
                mStream.Close();
                if (string.IsNullOrEmpty(keyExportName))
                {
                    useTemp = true;
                    string tempPath = Path.GetTempPath();
                    keyExportName = Path.Combine(tempPath, Guid.NewGuid().ToString() + ".tmppgp");
                }
                File.WriteAllText(keyExportName, outstr);
                keyExportName = "";
                //Debug.Assert(secKey.PublicKey.IsRevoked() == true);
                break;

            case SignatureOperation.SetKeyExpiry:
                break;

            case SignatureOperation.CertifyKey:
                break;

            default:
                break;
            }


            if (secKey.PublicKey != null)
            {
                if (string.IsNullOrEmpty(keyExportName))
                {
                    useTemp = true;
                    string tempPath = Path.GetTempPath();
                    keyExportName = Path.Combine(tempPath, Guid.NewGuid().ToString() + ".tmppgp");
                }
                ExportKey expKey = new ExportKey(keyDb);
                expKey.UpdateDbSecretKey(secKey, keyExportName);
                if (useTemp)
                {
                    //File.Delete(keyExportName);
                }
            }
        }
예제 #30
0
        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();
        }
        /*
         * create a clear text signed file.
         */
        public static void SignFile(
            //string fileName,
            Stream fIn,
            PgpSecretKey pgpSecKey,
            Stream outputStream,
            char[] pass,
            string digestName,
            bool version = true
            )
        {
            HashAlgorithmTag digest;

            if (string.Equals(digestName, "Sha256", StringComparison.CurrentCultureIgnoreCase))
            {
                digest = HashAlgorithmTag.Sha256;
            }
            else if (string.Equals(digestName, "Sha384", StringComparison.CurrentCultureIgnoreCase))
            {
                digest = HashAlgorithmTag.Sha384;
            }
            else if (string.Equals(digestName, "Sha512", StringComparison.CurrentCultureIgnoreCase))
            {
                digest = HashAlgorithmTag.Sha512;
            }
            else if (string.Equals(digestName, "MD5", StringComparison.CurrentCultureIgnoreCase))
            {
                digest = HashAlgorithmTag.MD5;
            }
            else if (string.Equals(digestName, "RipeMD160", StringComparison.CurrentCultureIgnoreCase))
            {
                digest = HashAlgorithmTag.RipeMD160;
            }
            else
            {
                digest = HashAlgorithmTag.Sha512;
            }

            // Instanciate signature generator.
            var sGen  = new PgpSignatureGenerator(pgpSecKey.PublicKey.Algorithm, digest);
            var spGen = new PgpSignatureSubpacketGenerator();

            // Extract private key
            PgpPrivateKey pgpPrivKey;

            try
            {
                pgpPrivKey = pgpSecKey.ExtractPrivateKey(pass);
                sGen.InitSign(PgpSignature.CanonicalTextDocument, pgpPrivKey);
            }
            catch
            {
                throw new PgpException("Wrong Passphrase, could not extract private key.");
            }

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

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

            var aOut = new ArmoredOutputStream(outputStream);

            if (version)
            {
                aOut.SetHeader("Version", "Posh-OpenPGP");
            }

            aOut.BeginClearText(digest);

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

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

            if (lookAhead != -1)
            {
                do
                {
                    lookAhead = ReadInputLine(lineOut, lookAhead, fIn);
                    sGen.Update((byte)'\r');
                    sGen.Update((byte)'\n');
                    ProcessLine(aOut, sGen, lineOut.ToArray());
                }while (lookAhead != -1);
            }

            fIn.Close();
            aOut.EndClearText();
            var bOut = new BcpgOutputStream(aOut);

            sGen.Generate().Encode(bOut);
            aOut.Close();
        }
예제 #32
0
        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;
        }
예제 #33
0
        private void GenerateAndSign()
        {
            SecureRandom random = SecureRandom.GetInstance("SHA1PRNG");

            IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator("ECDSA");

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

            AsymmetricCipherKeyPair kpSign = keyGen.GenerateKeyPair();

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

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

            //
            // try a signature
            //
            PgpSignatureGenerator signGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.ECDsa, HashAlgorithmTag.Sha256);

            signGen.InitSign(PgpSignature.BinaryDocument, ecdsaKeyPair.PrivateKey);

            signGen.Update(msg);

            PgpSignature sig = signGen.Generate();

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

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

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

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

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

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

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

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


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

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

            if (!sig.Verify())
            {
                Fail("re-encoded signature failed to verify!");
            }
        }
        /*
         * create a clear text signed file.
         */
        private static void SignFile(
            string fileName,
            Stream keyIn,
            Stream outputStream,
            char[]      pass,
            string digestName)
        {
            HashAlgorithmTag digest;

            if (digestName.Equals("SHA256"))
            {
                digest = HashAlgorithmTag.Sha256;
            }
            else if (digestName.Equals("SHA384"))
            {
                digest = HashAlgorithmTag.Sha384;
            }
            else if (digestName.Equals("SHA512"))
            {
                digest = HashAlgorithmTag.Sha512;
            }
            else if (digestName.Equals("MD5"))
            {
                digest = HashAlgorithmTag.MD5;
            }
            else if (digestName.Equals("RIPEMD160"))
            {
                digest = HashAlgorithmTag.RipeMD160;
            }
            else
            {
                digest = HashAlgorithmTag.Sha1;
            }

            PgpSecretKey                   pgpSecKey  = PgpExampleUtilities.ReadSecretKey(keyIn);
            PgpPrivateKey                  pgpPrivKey = pgpSecKey.ExtractPrivateKey(pass);
            PgpSignatureGenerator          sGen       = new PgpSignatureGenerator(pgpSecKey.PublicKey.Algorithm, digest);
            PgpSignatureSubpacketGenerator spGen      = new PgpSignatureSubpacketGenerator();

            sGen.InitSign(PgpSignature.CanonicalTextDocument, pgpPrivKey);

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

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

            Stream fIn = File.OpenRead(fileName);
            ArmoredOutputStream aOut = new ArmoredOutputStream(outputStream);

            aOut.BeginClearText(digest);

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

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

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

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

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

            fIn.Close();

            aOut.EndClearText();

            BcpgOutputStream bOut = new BcpgOutputStream(aOut);

            sGen.Generate().Encode(bOut);

            aOut.Close();
        }
예제 #35
0
        /// <summary>
        /// Sign a file with PGP signature. See documentation at https://github.com/CommunityHiQ/Frends.Community.PgpSignature Returns: Object {string FilePath}
        /// </summary>
        public static Result PGPSignFile(Input input)
        {
            HashAlgorithmTag digest;

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


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

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

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

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

            Stream outputStream = File.Create(input.OutputFile);
            ArmoredOutputStream armoredOutputStream = new ArmoredOutputStream(outputStream);
            BcpgOutputStream    bOut = new BcpgOutputStream(armoredOutputStream);

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

            FileInfo file = new FileInfo(input.InputFile);
            PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator();
            Stream     lOut = lGen.Open(bOut, PgpLiteralData.Binary, file);
            FileStream fIn  = file.OpenRead();
            int        ch;

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

            fIn.Close();
            lGen.Close();
            sGen.Generate().Encode(bOut);
            armoredOutputStream.Close();
            outputStream.Close();

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

            return(ret);
        }
		private void generateTest(
			string message,
			string type)
		{
			PgpSecretKey                    pgpSecKey = ReadSecretKey(new MemoryStream(secretKey));
			PgpPrivateKey                   pgpPrivKey = pgpSecKey.ExtractPrivateKey("".ToCharArray());
			PgpSignatureGenerator           sGen = new PgpSignatureGenerator(pgpSecKey.PublicKey.Algorithm, HashAlgorithmTag.Sha256);
			PgpSignatureSubpacketGenerator  spGen = new PgpSignatureSubpacketGenerator();

			sGen.InitSign(PgpSignature.CanonicalTextDocument, pgpPrivKey);

			IEnumerator    it = pgpSecKey.PublicKey.GetUserIds().GetEnumerator();
			if (it.MoveNext())
			{
				spGen.SetSignerUserId(false, (string)it.Current);
				sGen.SetHashedSubpackets(spGen.Generate());
			}

			MemoryStream bOut = new MemoryStream();
			ArmoredOutputStream aOut = new ArmoredOutputStream(bOut);
			MemoryStream bIn = new MemoryStream(Encoding.ASCII.GetBytes(message), false);

			aOut.BeginClearText(HashAlgorithmTag.Sha256);

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

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

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

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

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

			aOut.EndClearText();

			BcpgOutputStream bcpgOut = new BcpgOutputStream(aOut);

			sGen.Generate().Encode(bcpgOut);

			aOut.Close();

			byte[] bs = bOut.ToArray();
			messageTest(Encoding.ASCII.GetString(bs, 0, bs.Length), type);
		}
예제 #37
0
        // Based on http://jopinblog.wordpress.com/2008/06/23/pgp-single-pass-sign-and-encrypt-with-bouncy-castle/
        /// <summary>
        ///
        /// </summary>
        /// <param name="actualFileName"></param>
        /// <param name="embeddedFileName"></param>
        /// <param name="pgpSecKey"></param>
        /// <param name="outputFileName"></param>
        /// <param name="password"></param>
        /// <param name="armor"></param>
        /// <param name="withIntegrityCheck"></param>
        /// <param name="encKeys"></param>
        /// <param name="compressionName"></param>
        /// <param name="digestName"></param>
        public static void SignAndEncryptFile(string actualFileName,
                                              string embeddedFileName,
                                              PgpSecretKey pgpSecKey,
                                              string outputFileName,
                                              char[] password,
                                              bool armor,
                                              bool withIntegrityCheck,
                                              PgpPublicKey[] encKeys,
                                              string compressionName,
                                              string digestName)
        {
            CompressionAlgorithmTag comptype;

            if (string.Equals(compressionName, "Uncompressed", StringComparison.CurrentCultureIgnoreCase))
            {
                comptype = CompressionAlgorithmTag.Uncompressed;
            }
            else if (string.Equals(compressionName, "Zip", StringComparison.CurrentCultureIgnoreCase))
            {
                comptype = CompressionAlgorithmTag.Zip;
            }
            else if (string.Equals(compressionName, "Zlib", StringComparison.CurrentCultureIgnoreCase))
            {
                comptype = CompressionAlgorithmTag.ZLib;
            }
            else if (string.Equals(compressionName, "BZip2", StringComparison.CurrentCultureIgnoreCase))
            {
                comptype = CompressionAlgorithmTag.BZip2;
            }
            else
            {
                comptype = CompressionAlgorithmTag.Zip;
            }

            HashAlgorithmTag digest;

            if (string.Equals(digestName, "Sha256", StringComparison.CurrentCultureIgnoreCase))
            {
                digest = HashAlgorithmTag.Sha256;
            }
            else if (string.Equals(digestName, "Sha384", StringComparison.CurrentCultureIgnoreCase))
            {
                digest = HashAlgorithmTag.Sha384;
            }
            else if (string.Equals(digestName, "Sha512", StringComparison.CurrentCultureIgnoreCase))
            {
                digest = HashAlgorithmTag.Sha512;
            }
            else if (string.Equals(digestName, "MD5", StringComparison.CurrentCultureIgnoreCase))
            {
                digest = HashAlgorithmTag.MD5;
            }
            else if (string.Equals(digestName, "RipeMD160", StringComparison.CurrentCultureIgnoreCase))
            {
                digest = HashAlgorithmTag.RipeMD160;
            }
            else
            {
                digest = HashAlgorithmTag.Sha512;
            }
            const int bufferSize   = 1 << 16; // should always be power of 2
            Stream    outputStream = File.Open(outputFileName, FileMode.Create);

            if (armor)
            {
                var aOutStream = new ArmoredOutputStream(outputStream);
                aOutStream.SetHeader("Version", "Posh-OpenPGP");
                outputStream = aOutStream;
            }

            // Init encrypted data generator
            var encryptedDataGenerator =
                new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, withIntegrityCheck, new SecureRandom());

            // add keys to encrypt to
            foreach (var encKey in encKeys)
            {
                encryptedDataGenerator.AddMethod(encKey);
            }
            var encryptedOut = encryptedDataGenerator.Open(outputStream, new byte[bufferSize]);

            // Init compression
            var compressedDataGenerator = new PgpCompressedDataGenerator(comptype);
            var compressedOut           = compressedDataGenerator.Open(encryptedOut);

            // Init signature
            PgpPrivateKey pgpPrivKey;

            try
            {
                pgpPrivKey = pgpSecKey.ExtractPrivateKey(password);
            }
            catch
            {
                throw new PgpException("Wrong Passphrase, could not extract private key.");
            }
            var signatureGenerator = new PgpSignatureGenerator(pgpSecKey.PublicKey.Algorithm, digest);

            signatureGenerator.InitSign(PgpSignature.BinaryDocument, pgpPrivKey);

            foreach (string userId in pgpSecKey.PublicKey.GetUserIds())
            {
                var spGen = new PgpSignatureSubpacketGenerator();
                spGen.SetSignerUserId(false, userId);
                signatureGenerator.SetHashedSubpackets(spGen.Generate());

                // Just the first one!
                break;
            }
            signatureGenerator.GenerateOnePassVersion(false).Encode(compressedOut);

            // Create the Literal Data generator output stream
            var literalDataGenerator = new PgpLiteralDataGenerator();
            var embeddedFile         = new FileInfo(embeddedFileName);
            var actualFile           = new FileInfo(actualFileName);

            var literalOut = literalDataGenerator.Open(compressedOut, PgpLiteralData.Binary,
                                                       embeddedFile.Name, DateTime.UtcNow, new byte[bufferSize]);

            // Open the input file
            var inputStream = actualFile.OpenRead();
            var buf         = new byte[bufferSize];
            int len;

            while ((len = inputStream.Read(buf, 0, buf.Length)) > 0)
            {
                literalOut.Write(buf, 0, len);
                signatureGenerator.Update(buf, 0, len);
            }

            literalOut.Close();
            literalDataGenerator.Close();
            signatureGenerator.Generate().Encode(compressedOut);
            compressedOut.Close();
            compressedDataGenerator.Close();
            encryptedOut.Close();
            encryptedDataGenerator.Close();
            inputStream.Close();
            if (armor)
            {
                outputStream.Close();
            }
        }
예제 #38
0
        /// <summary>
        ///     Signs the specified byte array using the specified key after unlocking the key with the specified passphrase.
        /// </summary>
        /// <param name="bytes">The byte array containing the payload to sign.</param>
        /// <param name="key">The PGP key to be used to sign the payload.</param>
        /// <param name="passphrase">The passphrase used to unlock the PGP key.</param>
        /// <returns>A byte array containing the generated PGP signature.</returns>
        public static byte[] Sign(byte[] bytes, string key, string passphrase)
        {
            // prepare a memory stream to hold the signature
            MemoryStream memoryStream = new MemoryStream();

            // prepare an armored output stream to produce an armored ASCII signature
            Stream outputStream = new ArmoredOutputStream(memoryStream);

            // retrieve the keys
            PgpSecretKey  secretKey  = ReadSecretKeyFromString(key);
            PgpPrivateKey privateKey = secretKey.ExtractPrivateKey(passphrase.ToCharArray());

            // create and initialize a signature generator
            PgpSignatureGenerator signatureGenerator = new PgpSignatureGenerator(secretKey.PublicKey.Algorithm, HashAlgorithmTag.Sha512);

            signatureGenerator.InitSign(PgpSignature.BinaryDocument, privateKey);

            // retrieve the first user id contained within the public key and use it to set the signature signer
            foreach (string userId in secretKey.PublicKey.GetUserIds())
            {
                PgpSignatureSubpacketGenerator signatureSubpacketGenerator = new PgpSignatureSubpacketGenerator();
                signatureSubpacketGenerator.SetSignerUserId(false, userId);
                signatureGenerator.SetHashedSubpackets(signatureSubpacketGenerator.Generate());

                break;
            }

            // prepare a compressed data generator and compressed output stream to compress the data
            PgpCompressedDataGenerator compressedDataGenerator = new PgpCompressedDataGenerator(CompressionAlgorithmTag.ZLib);
            Stream compressedOutputStream = compressedDataGenerator.Open(outputStream);

            // generate the signature taken pretty much verbatim from the bouncycastle example; not sure what all of it does.
            BcpgOutputStream bcpgOutputStream = new BcpgOutputStream(compressedOutputStream);

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

            PgpLiteralDataGenerator literalDataGenerator = new PgpLiteralDataGenerator();
            Stream literalOutputStream = literalDataGenerator.Open(bcpgOutputStream, PgpLiteralData.Binary, "signatureData", DateTime.UtcNow, new byte[4092]);

            foreach (byte b in bytes)
            {
                literalOutputStream.WriteByte(b);
                signatureGenerator.Update(b);
            }

            literalDataGenerator.Close();

            signatureGenerator.Generate().Encode(bcpgOutputStream);

            compressedDataGenerator.Close();

            outputStream.Close();

            // fetch a byte array containing the contents of the memory stream
            byte[] retVal = memoryStream.ToArray();

            // close the memory stream
            memoryStream.Close();

            // return the generated signature
            return(retVal);
        }
        private static void writeAndSign(Stream ouput, Stream literalout, FileStream inputFile, PgpSignatureGenerator sigGen)
        {
            int length = 0;

            byte[] buf = new byte[BufferSize];
            while ((length = inputFile.Read(buf, 0, buf.Length)) > 0)
            {
                literalout.Write(buf, 0, length);
                sigGen.Update(buf, 0, length);
            }
            sigGen.Generate().Encode(ouput);
        }
        private void doTestSig(
			PublicKeyAlgorithmTag	encAlgorithm,
			HashAlgorithmTag		hashAlgorithm,
			IPgpPublicKey			pubKey,
			IPgpPrivateKey			privKey)
        {
            MemoryStream bOut = new MemoryStream();
            MemoryStream testIn = new MemoryStream(TEST_DATA, false);
            PgpSignatureGenerator sGen = new PgpSignatureGenerator(encAlgorithm, hashAlgorithm);

            sGen.InitSign(PgpSignature.BinaryDocument, privKey);
            sGen.GenerateOnePassVersion(false).Encode(bOut);

            PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator();
            Stream lOut = lGen.Open(
                new UncloseableStream(bOut),
                PgpLiteralData.Binary,
                "_CONSOLE",
                TEST_DATA.Length * 2,
                DateTime.UtcNow);

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

            lOut.Write(TEST_DATA, 0, TEST_DATA.Length);
            sGen.Update(TEST_DATA);

            lGen.Close();

            sGen.Generate().Encode(bOut);

            verifySignature(bOut.ToArray(), hashAlgorithm, pubKey, TEST_DATA);
        }
예제 #41
0
        void SignAndEncryptFile()
        {
            const int BUFFER_SIZE = 1 << 16; // should always be power of 2

            var OutStream = OutFile.OpenWrite();

            PgpEncryptedDataGenerator encryptedDataGenerator = new PgpEncryptedDataGenerator(symAlgTag, WithIntegrityCheck, new SecureRandom());

            foreach (var publicKey in PublicKeys)
            {
                var encKey = ReadPublicKey(publicKey);
                encryptedDataGenerator.AddMethod(encKey);
            }

            Stream outputStream = OutStream;

            if (Armor)
            {
                outputStream = new ArmoredOutputStream(outputStream);
            }

            Stream encryptedOut = encryptedDataGenerator.Open(outputStream, new byte[BUFFER_SIZE]);

            if (Compress)
            {
                // Init compression
                PgpCompressedDataGenerator compressedDataGenerator = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip);
                encryptedOut = compressedDataGenerator.Open(encryptedOut);
            }

            //signing
            List <PgpSignatureGenerator> pgpSignatureGenerators = new List <PgpSignatureGenerator>();

            foreach (var privateKeyInfo in PrivateKeys)
            {
                PgpSecretKey  pgpSecKey  = ReadSecretKey(privateKeyInfo.PrivateKeyStream);
                PgpPrivateKey pgpPrivKey = pgpSecKey.ExtractPrivateKey(privateKeyInfo.PrivateKeyPassword == null ? null : privateKeyInfo.PrivateKeyPassword.ToCharArray());

                PgpSignatureGenerator signatureGenerator = new PgpSignatureGenerator(pgpSecKey.PublicKey.Algorithm, HashAlgorithmTag.Sha1);
                signatureGenerator.InitSign(PgpSignature.BinaryDocument, pgpPrivKey);

                foreach (string userId in pgpSecKey.PublicKey.GetUserIds())
                {
                    PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator();
                    spGen.SetSignerUserId(false, userId);
                    signatureGenerator.SetHashedSubpackets(spGen.Generate());
                    // Just the first one!
                    break;
                }

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

                pgpSignatureGenerators.Add(signatureGenerator);
            }
            // Create the Literal Data generator output stream
            PgpLiteralDataGenerator literalDataGenerator = new PgpLiteralDataGenerator();
            Stream literalOut = literalDataGenerator.Open(encryptedOut, PgpLiteralData.Binary, InFile.Name, InFile.LastWriteTime, new byte[BUFFER_SIZE]);

            // Open the input file
            FileStream inputStream = InFile.OpenRead();

            byte[] buf = new byte[BUFFER_SIZE];
            int    len;

            while ((len = inputStream.Read(buf, 0, buf.Length)) > 0)
            {
                literalOut.Write(buf, 0, len);
                foreach (var signatureGenerator in pgpSignatureGenerators)
                {
                    signatureGenerator.Update(buf, 0, len);
                }
            }

            literalOut.Close();
            literalDataGenerator.Close();
            foreach (var signatureGenerator in pgpSignatureGenerators)
            {
                signatureGenerator.Generate().Encode(encryptedOut);
            }
            encryptedOut.Close();
            encryptedOut.Close();
            encryptedDataGenerator.Close();
            inputStream.Close();


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

            OutStream.Close();
        }
        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();
        }
예제 #43
0
 private static void WriteOutputAndSign(Stream compressedOut, Stream literalOut, byte[] unencryptedBytes, PgpSignatureGenerator sigGenerator)
 {
     literalOut.Write(unencryptedBytes, 0, unencryptedBytes.Length);
     sigGenerator.Update(unencryptedBytes, 0, unencryptedBytes.Length);
     sigGenerator.Generate().Encode(compressedOut);
 }