Example #1
0
 /// <summary>
 /// Attempt to sign then encrypt a message using PGP with the specified private and public keys.
 /// </summary>
 /// <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="recipientPublicKey">BouncyCastle public key 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>
 /// <returns>Whether the encryption completed successfully.</returns>
 public bool PgpSignAndEncrypt(PgpPublicKey senderPublicKey, PgpPrivateKey senderPrivateKey, PgpPublicKey recipientPublicKey, HashAlgorithmTag hashAlgorithmTag = HashAlgorithmTag.Sha256, SymmetricKeyAlgorithmTag symmetricKeyAlgorithmTag = SymmetricKeyAlgorithmTag.TripleDes)
 {
     return(PgpSignAndEncrypt(senderPublicKey, senderPrivateKey, new List <PgpPublicKey>()
     {
         recipientPublicKey
     }, hashAlgorithmTag, symmetricKeyAlgorithmTag));
 }
        /// <summary>
        /// Calculates the signature for this package.
        /// </summary>
        /// <param name="package">
        /// The package for whcih to calculate the signature.
        /// </param>
        /// <param name="privateKey">
        /// The private key to use.
        /// </param>
        /// <param name="compressedPayloadStream">
        /// The compressed payload.
        /// </param>
        public void CalculateSignature(RpmPackage package, PgpPrivateKey privateKey, Stream compressedPayloadStream)
        {
            RpmSignature signature = new RpmSignature(package);

            using (MemoryStream headerStream = this.GetHeaderStream(package))
                using (ConcatStream headerAndPayloadStream = new ConcatStream(leaveOpen: true, streams: new Stream[] { headerStream, compressedPayloadStream }))
                {
                    SHA1 sha = SHA1.Create();
                    signature.Sha1Hash = sha.ComputeHash(headerStream);

                    MD5 md5 = MD5.Create();
                    signature.MD5Hash = md5.ComputeHash(headerAndPayloadStream);

                    // Verify the PGP signatures
                    // 3 for the header
                    headerStream.Position        = 0;
                    signature.HeaderPgpSignature = PgpSigner.Sign(privateKey, headerStream);

                    headerAndPayloadStream.Position        = 0;
                    signature.HeaderAndPayloadPgpSignature = PgpSigner.Sign(privateKey, headerAndPayloadStream);

                    // Verify the signature size (header + compressed payload)
                    signature.HeaderAndPayloadSize = (int)headerAndPayloadStream.Length;
                }

            // Verify the payload size (header + uncompressed payload)

            using (Stream payloadStream = RpmPayloadReader.GetDecompressedPayloadStream(package, compressedPayloadStream))
            {
                signature.UncompressedPayloadSize = (int)payloadStream.Length;
            }
        }
Example #3
0
        /// <summary>
        /// Helper for creating a PgpSignatureGenerator from private key file and its password
        /// </summary>
        /// <param name="stream">Stream to use for signature initialization</param>
        /// <param name="input">Encryption task input</param>
        /// <returns>PgpSignatureGenerator to be used when signing a file</returns>
        internal static PgpSignatureGenerator InitPgpSignatureGenerator(Stream stream, PgpEncryptInput input)
        {
            HashAlgorithmTag hashAlgorithm = input.SigningSettings.SignatureHashAlgorithm.ConvertEnum <HashAlgorithmTag>();

            try
            {
                PgpSecretKey  secretKey  = ReadSecretKey(input.SigningSettings.PrivateKeyFile);
                PgpPrivateKey privateKey = secretKey.ExtractPrivateKey(input.SigningSettings.PrivateKeyPassword.ToCharArray());

                var pgpSignatureGenerator = new PgpSignatureGenerator(secretKey.PublicKey.Algorithm, hashAlgorithm);
                pgpSignatureGenerator.InitSign(PgpSignature.BinaryDocument, privateKey);

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

                pgpSignatureGenerator.GenerateOnePassVersion(false).Encode(stream);
                return(pgpSignatureGenerator);
            }
            catch (PgpException e)
            {
                throw new Exception("Private key extraction failed, password might be incorrect", e);
            }
        }
Example #4
0
        /*.......................................................................數位簽章開始*/


        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);
            }
            PgpSecretKey          pgpSec     = PgpExampleUtilities.ReadSecretKey(keyIn);
            PgpPrivateKey         pgpPrivKey = pgpSec.ExtractPrivateKey(pass);
            PgpSignatureGenerator sGen       = new PgpSignatureGenerator(pgpSec.PublicKey.Algorithm, HashAlgorithmTag.Sha256);

            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();
            }
        }
Example #5
0
        private static byte[] RevokePublicKey(PgpSecretKey sKey, char[] sPass, PgpPublicKey keyToSign, bool armour)
        {
            Stream os = new MemoryStream();

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

            PgpPrivateKey         privKey = sKey.ExtractPrivateKey(sPass);
            PgpSignatureGenerator sGen    = new PgpSignatureGenerator(sKey.PublicKey.Algorithm, HashAlgorithmTag.Sha1);

            sGen.InitSign(PgpSignature.KeyRevocation, privKey);
            BcpgOutputStream bOut = new BcpgOutputStream(os);

            sGen.GenerateOnePassVersion(false).Encode(bOut);
            PgpSignatureSubpacketGenerator spGen = new PgpSignatureSubpacketGenerator();

            spGen.SetRevocable(false, true);
            DateTime baseDate = new DateTime(1970, 1, 1);
            TimeSpan tSpan    = DateTime.UtcNow - baseDate;

            spGen.SetSignatureExpirationTime(false, tSpan.Seconds);
            PgpSignatureSubpacketVector packetVector = spGen.Generate();

            sGen.SetHashedSubpackets(packetVector);
            bOut.Flush();

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

            return(PgpPublicKey.AddCertification(keyToSign, sGen.Generate()).GetEncoded());
        }
Example #6
0
        /// <summary>
        /// Attempt to sign then encrypt a message using PGP with the specified private and public keys.
        /// </summary>
        /// <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>
        /// <returns>Whether the encryption completed successfully.</returns>
        public bool PgpSignAndEncrypt(PgpPublicKey senderPublicKey, PgpPrivateKey senderPrivateKey, IEnumerable <PgpPublicKey> recipientPublicKeys, HashAlgorithmTag hashAlgorithmTag = HashAlgorithmTag.Sha256, SymmetricKeyAlgorithmTag symmetricKeyAlgorithmTag = SymmetricKeyAlgorithmTag.TripleDes)
        {
            // Ensure a valid encoding.
            if (BodyEncoding == null)
            {
                BodyEncoding = Encoding.UTF8;
            }

            // Attempt to sign.
            bool signedAndEncrypted = false;

            using (MemoryStream signedAndEncryptedMessageStream = new MemoryStream())
            {
                // Attempt to encrypt the message.
                signedAndEncrypted = Pgp.SignAndEncrypt(BodyEncoding.GetBytes(Body), "", signedAndEncryptedMessageStream, senderPublicKey, senderPrivateKey, recipientPublicKeys, hashAlgorithmTag, symmetricKeyAlgorithmTag, true);

                if (signedAndEncrypted)
                {
                    signedAndEncrypted = true;

                    rawBody = BodyEncoding.GetString(signedAndEncryptedMessageStream.ToArray());
                }
            }

            return(signedAndEncrypted);
        }
Example #7
0
 /// <summary>
 /// Attempt to decrypt a PGP protected message using the matching private key.
 /// </summary>
 /// <param name="message">Byte array containing the message to decrypt.</param>
 /// <param name="decryptedMessageStream">Stream to write the decrypted message into.</param>
 /// <param name="recipientPrivateKey">The BouncyCastle private key to be used for decryption.</param>
 /// <remarks>The message should be passed in without ASCII Armor.</remarks>
 /// <returns>Whether the decryption completed successfully.</returns>
 public static bool Decrypt(byte[] message, Stream decryptedMessageStream, PgpPrivateKey recipientPrivateKey)
 {
     using (MemoryStream messageStream = new MemoryStream(message))
     {
         return(Decrypt(messageStream, decryptedMessageStream, recipientPrivateKey));
     }
 }
 /// <summary>
 /// Creates a RPM Package.
 /// </summary>
 /// <param name="archiveEntries">
 /// The archive entries which make up the RPM package.
 /// </param>
 /// <param name="payloadStream">
 /// A <see cref="Stream"/> which contains the CPIO archive for the RPM package.
 /// </param>
 /// <param name="name">
 /// The name of the package.
 /// </param>
 /// <param name="version">
 /// The version of the software.
 /// </param>
 /// <param name="arch">
 /// The architecture targetted by the package.
 /// </param>
 /// <param name="release">
 /// The release version.
 /// </param>
 /// <param name="createUser">
 /// <see langword="true"/> to create a user account; otherwise, <see langword="false"/>.
 /// </param>
 /// <param name="userName">
 /// The name of the user account to create.
 /// </param>
 /// <param name="installService">
 /// <see langword="true"/> to install a system service, otherwise, <see langword="false"/>.
 /// </param>
 /// <param name="serviceName">
 /// The name of the system service to create.
 /// </param>
 /// <param name="prefix">
 /// A prefix to use.
 /// </param>
 /// <param name="additionalDependencies">
 /// Additional dependencies to add to the RPM package.
 /// </param>
 /// <param name="additionalMetadata">
 /// Any additional metadata.
 /// </param>
 /// <param name="privateKey">
 /// The private key to use when signing the package.
 /// </param>
 /// <param name="targetStream">
 /// The <see cref="Stream"/> to which to write the package.
 /// </param>
 public void CreatePackage(
     List <ArchiveEntry> archiveEntries,
     Stream payloadStream,
     string name,
     string version,
     string arch,
     string release,
     bool createUser,
     string userName,
     bool installService,
     string serviceName,
     string prefix,
     IEnumerable <PackageDependency> additionalDependencies,
     Action <RpmMetadata> additionalMetadata,
     PgpPrivateKey privateKey,
     Stream targetStream)
 {
     this.CreatePackage(
         archiveEntries,
         payloadStream,
         name,
         version,
         arch,
         release,
         createUser,
         userName,
         installService,
         serviceName,
         prefix,
         additionalDependencies,
         additionalMetadata,
         new PackageSigner(privateKey),
         targetStream);
 }
Example #9
0
        private void DoTestKey(BigInteger keyId, string passphrase, bool utf8)
        {
            PgpSecretKeyRingBundle secretKeyRing = LoadSecretKeyCollection("secring.gpg");

            PgpSecretKeyRing secretKey = secretKeyRing.GetSecretKeyRing(keyId.LongValue);

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

            PgpSecretKey key = secretKey.GetSecretKey();

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

            try
            {
                char[] pass = passphrase.ToCharArray();

                PgpPrivateKey privateKey = utf8
                    ?   key.ExtractPrivateKeyUtf8(pass)
                    :   key.ExtractPrivateKey(pass);

                Assert.IsTrue(privateKey.KeyId == keyId.LongValue);
            }
            catch (PgpException e)
            {
                throw new PgpException("Password incorrect!", e);
            }

            // all fine!
        }
Example #10
0
        public static Stream Decrypt(Stream inputStream, PgpPrivateKey privateKey)
        {
            using Stream decoderStream = PgpUtilities.GetDecoderStream(inputStream);
            PgpObjectFactory          decoderFactory = new(decoderStream);
            PgpEncryptedDataList      dataList       = decoderFactory.NextPgpObject() as PgpEncryptedDataList ?? (PgpEncryptedDataList)decoderFactory.NextPgpObject();
            PgpPublicKeyEncryptedData data           = dataList.GetEncryptedDataObjects().Cast <PgpPublicKeyEncryptedData>().First();

            using Stream dataStream = data.GetDataStream(privateKey);
            PgpObjectFactory dataFactory = new(dataStream);

            if (dataFactory.NextPgpObject() is not PgpCompressedData compressedData)
            {
                throw new Exception();
            }
            using Stream compressedStream = compressedData.GetDataStream();
            PgpObjectFactory factory = new(compressedStream);
            PgpLiteralData   literal = factory.NextPgpObject() as PgpLiteralData ?? (PgpLiteralData)factory.NextPgpObject();
            MemoryStream     output  = new();

            using (Stream input = literal.GetInputStream())
            {
                Streams.PipeAll(input, output);
            }
            output.Seek(0L, SeekOrigin.Begin);
            return(output);
        }
Example #11
0
        private void doTestTextSig(
            PgpHashAlgorithm hashAlgorithm,
            PgpKey pubKey,
            PgpPrivateKey privKey,
            byte[] data,
            byte[] canonicalData,
            int version = 4)
        {
            MemoryStream bOut             = new MemoryStream();
            var          messageGenerator = new PgpMessageGenerator(bOut);

            using (var signingGenerator = messageGenerator.CreateSigned(PgpSignatureType.CanonicalTextDocument, privKey, PgpHashAlgorithm.Sha1, version))
                using (var literalStream = signingGenerator.CreateLiteral(PgpDataFormat.Text, "_CONSOLE", DateTime.UtcNow))
                {
                    literalStream.Write(data);
                    literalStream.Write(canonicalData);
                }

            /*if (sig.CreationTime == DateTimeOffset.FromUnixTimeSeconds(0).DateTime)
             * {
             *  Fail("creation time not set in v4 signature");
             * }*/

            verifySignature(bOut.ToArray(), hashAlgorithm, pubKey, canonicalData);
        }
        public String DecryptKeycode(String privateKeyStr, String encryptedKeycode)
        {
            byte[] rawMessage = System.Text.Encoding.ASCII.GetBytes(encryptedKeycode);

            Stream inputStream = new MemoryStream(rawMessage);

            inputStream = PgpUtilities.GetDecoderStream(inputStream);

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

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

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

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

            PgpPublicKeyEncryptedData dataObject = null;

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

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

            Stream dataStream = dataObject.GetDataStream(key);

            PgpObjectFactory pgpFact = new PgpObjectFactory(dataStream);

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

            Stream unc = ld.GetInputStream();

            String keycode;

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

            return(keycode);
        }
Example #13
0
        private void MixedTest(
            PgpPrivateKey pgpPrivKey,
            PgpKey pgpPubKey)
        {
            byte[] text = Encoding.ASCII.GetBytes("hello world!\n");

            MemoryStream bcOut            = new MemoryStream();
            var          messageGenerator = new PgpMessageGenerator(bcOut);

            using (var encryptedGenerator = messageGenerator.CreateEncrypted(PgpSymmetricKeyAlgorithm.Aes128, withIntegrityPacket: true))
            {
                encryptedGenerator.AddMethod(pgpPubKey);
                encryptedGenerator.AddMethod("password", PgpHashAlgorithm.Sha1);
                using (var literalStream = encryptedGenerator.CreateLiteral(PgpDataFormat.Binary, "_CONSOLE", DateTime.UtcNow))
                {
                    literalStream.Write(text);
                }
            }
            byte[] encData = bcOut.ToArray();

            // Asymmetric
            var encryptedMessage = (PgpEncryptedMessage)PgpMessage.ReadMessage(encData);
            var literalMessage   = (PgpLiteralMessage)encryptedMessage.DecryptMessage(pgpPrivKey);

            CheckLiteralData(literalMessage, text);

            // PBE
            encryptedMessage = (PgpEncryptedMessage)PgpMessage.ReadMessage(encData);
            literalMessage   = (PgpLiteralMessage)encryptedMessage.DecryptMessage("password");
            CheckLiteralData(literalMessage, text);
        }
Example #14
0
        private void PerformTestSig(
            PgpHashAlgorithm hashAlgorithm,
            PgpKey pubKey,
            PgpPrivateKey privKey)
        {
            const string data = "hello world!";

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

            MemoryStream bOut             = new MemoryStream();
            var          messageGenerator = new PgpMessageGenerator(bOut);

            using (var compressedGenerator = messageGenerator.CreateCompressed(PgpCompressionAlgorithm.Zip))
                using (var signingGenerator = compressedGenerator.CreateSigned(PgpSignatureType.BinaryDocument, privKey, hashAlgorithm))
                    using (var literalStream = signingGenerator.CreateLiteral(PgpDataFormat.Binary, "_CONSOLE", testDateTime))
                    {
                        literalStream.Write(dataBytes);
                    }

            // Verify generated signature
            bOut.Position = 0;
            var compressedMessage = (PgpCompressedMessage)PgpMessage.ReadMessage(bOut);
            var signedMessage     = (PgpSignedMessage)compressedMessage.ReadMessage();
            var literalMessage    = (PgpLiteralMessage)signedMessage.ReadMessage();

            Assert.AreEqual(testDateTime, literalMessage.ModificationTime);
            literalMessage.GetStream().CopyTo(Stream.Null);
            Assert.IsTrue(signedMessage.Verify(pubKey));
        }
        private static PgpObjectFactory getClearDataStream(PgpPrivateKey privateKey, PgpPublicKeyEncryptedData publicKeyED)
        {
            Stream           clearStream  = publicKeyED.GetDataStream(privateKey);
            PgpObjectFactory clearFactory = new PgpObjectFactory(clearStream);

            return(clearFactory);
        }
Example #16
0
        public void Generate()
        {
            // Master/Signing key
            var ecdsa = ECDsa.Create(ECCurve.NamedCurves.nistP256);
            // Encryption key
            var ecdh = ECDiffieHellman.Create(ECCurve.NamedCurves.nistP256);

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

            keyRingGen.AddSubKey(ecdh);

            PgpPublicKeyRing pubRing = keyRingGen.GeneratePublicKeyRing();

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

            PgpSecretKeyRing secRing = keyRingGen.GenerateSecretKeyRing();

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

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

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

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

            PgpPrivateKey pgpPrivKey = secRing.GetSecretKey().ExtractPrivateKey(passPhrase);
        }
Example #17
0
        /*
         * Helper for above.
         */
        static byte [] SignPublicKey(
            PgpSecretKey secretKey,
            string password,
            PgpPublicKey keyToBeSigned,
            bool isCertain)
        {
            // Extracting private key, and getting ready to create a signature.
            PgpPrivateKey         pgpPrivKey = secretKey.ExtractPrivateKey(password.ToCharArray());
            PgpSignatureGenerator sGen       = new PgpSignatureGenerator(secretKey.PublicKey.Algorithm, HashAlgorithmTag.Sha1);

            sGen.InitSign(isCertain ? PgpSignature.PositiveCertification : PgpSignature.CasualCertification, pgpPrivKey);

            // Creating a stream to wrap the results of operation.
            Stream           os   = new MemoryStream();
            BcpgOutputStream bOut = new BcpgOutputStream(os);

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

            // Creating a generator.
            PgpSignatureSubpacketGenerator spGen        = new PgpSignatureSubpacketGenerator();
            PgpSignatureSubpacketVector    packetVector = spGen.Generate();

            sGen.SetHashedSubpackets(packetVector);
            bOut.Flush();

            // Returning the signed public key.
            return(PgpPublicKey.AddCertification(keyToBeSigned, sGen.Generate()).GetEncoded());
        }
 public void decrypt(Stream input, string outputpath)
 {
     input = PgpUtilities.GetDecoderStream(input);
     try
     {
         PgpObjectFactory     pgpObjF = new PgpObjectFactory(input);
         PgpEncryptedDataList enc;
         PgpObject            obj = pgpObjF.NextPgpObject();
         if (obj is PgpEncryptedDataList)
         {
             enc = (PgpEncryptedDataList)obj;
         }
         else
         {
             enc = (PgpEncryptedDataList)pgpObjF.NextPgpObject();
         }
         PgpPrivateKey             privKey = pgpKeys.PrivateKey;
         PgpPublicKeyEncryptedData pbe     = null;
         foreach (PgpPublicKeyEncryptedData pked in enc.GetEncryptedDataObjects())
         {
             if (privKey != null)
             {
                 pbe = pked;
                 break;
             }
         }
         Stream           clear     = pbe.GetDataStream(privKey);
         PgpObjectFactory plainFact = new PgpObjectFactory(clear);
         PgpObject        message   = plainFact.NextPgpObject();
         if (message is PgpCompressedData)
         {
             PgpCompressedData cData      = (PgpCompressedData)message;
             Stream            compDataIn = cData.GetDataStream();
             PgpObjectFactory  o          = new PgpObjectFactory(compDataIn);
             message = o.NextPgpObject();
             if (message is PgpOnePassSignatureList)
             {
                 message = o.NextPgpObject();
                 PgpLiteralData Ld = null;
                 Ld = (PgpLiteralData)message;
                 Stream output = File.Create(outputpath + "\\" + Ld.FileName);
                 Stream unc    = Ld.GetInputStream();
                 Streams.PipeAll(unc, output);
             }
             else
             {
                 PgpLiteralData Ld = null;
                 Ld = (PgpLiteralData)message;
                 Stream output = File.Create(outputpath + "\\" + Ld.FileName);
                 Stream unc    = Ld.GetInputStream();
                 Streams.PipeAll(unc, output);
             }
         }
     }
     catch (Exception e)
     {
         throw new Exception(e.Message);
     }
 }
Example #19
0
        private PgpSignatureGenerator signatureGenerator(string keyPassPhrase)
        {
            PgpSignatureGenerator generator = new PgpSignatureGenerator(key.PublicKey.Algorithm, Org.BouncyCastle.Bcpg.HashAlgorithmTag.Sha512);
            PgpPrivateKey privateKey = extractPGPPrivateKey(keyPassPhrase.ToCharArray());

            init(generator, PgpPrivateKey);
            return generator;
        }
Example #20
0
        private string signEnvelopeData(string msg)
        {
            Stream privateKeyStream = getPrivateKeyStream(_privateKey);

            MemoryStream        result = new MemoryStream();
            ArmoredOutputStream aOut   = new ArmoredOutputStream(result);
            BcpgOutputStream    bOut   = null;

            char[] privateKeyPassword = _passPhrase.ToCharArray();
            var    utf8Encoding       = new System.Text.UTF8Encoding();

            try
            {
                PgpSecretKey                   sk     = readSecretKey(privateKeyStream);
                PgpPrivateKey                  pk     = sk.ExtractPrivateKey(privateKeyPassword);
                PgpSignatureGenerator          sigGen = new PgpSignatureGenerator(sk.PublicKey.Algorithm, HashAlgorithmTag.Sha256);
                PgpSignatureSubpacketGenerator spGen  = new PgpSignatureSubpacketGenerator();

                var enumerator = sk.PublicKey.GetUserIds().GetEnumerator();
                if (enumerator.MoveNext())
                {
                    spGen.SetSignerUserId(false, (string)enumerator.Current);
                    sigGen.SetHashedSubpackets(spGen.Generate());
                }

                aOut.BeginClearText(HashAlgorithmTag.Sha256);
                sigGen.InitSign(PgpSignature.CanonicalTextDocument, pk);
                byte[] msgBytes = utf8Encoding.GetBytes(msg);
                sigGen.Update(msgBytes, 0, msgBytes.Length);
                aOut.Write(msgBytes, 0, msgBytes.Length);
                bOut = new BcpgOutputStream(aOut);
                aOut.EndClearText();
                sigGen.Generate().Encode(bOut);
                using (BinaryReader br = new BinaryReader(result))
                {
                    br.BaseStream.Position = 0;
                    return(utf8Encoding.GetString(br.ReadBytes((int)result.Length)));
                }
            }
            catch (Exception e)
            { Console.WriteLine("This happened: " + e.Message);
              throw new Exception("Signing Failed: " + e.Message); }
            finally
            {
                try
                {
                    if (privateKeyStream != null)
                    {
                        privateKeyStream.Close();
                    }
                    //if(bOut != null)
                    //bOut.Close();
                    //aOut.Close();
                    result.Close();
                } catch (IOException) {}
            }
        }
        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);
        }
Example #22
0
 public bool Unlock(string password)
 {
     try {
         key = secret.ExtractPrivateKey(password.ToCharArray());
         return(true);
     } catch (Exception) {
         return(false);
     }
 }
        public PackageSigner(PgpPrivateKey privateKey)
        {
            if (privateKey == null)
            {
                throw new ArgumentNullException(nameof(privateKey));
            }

            this.privateKey = privateKey;
        }
        public static PgpKeyPair Convert(PublicKeyAlgorithmTag algorithmTag, AsymmetricKeyPair <AsymmetricRsaPublicKey, AsymmetricRsaPrivateKey> kp, DateTime date)
        {
            PublicKeyPacket pubPacket = new PublicKeyPacket(algorithmTag, date, new RsaPublicBcpgKey(kp.PublicKey.Modulus, kp.PublicKey.PublicExponent));

            PgpPublicKey  pubKey  = new PgpPublicKey(pubPacket, new PgpKeyFingerprintCalculator());
            PgpPrivateKey privKey = new PgpPrivateKey(pubKey.KeyId, pubPacket, new RsaSecretBcpgKey(kp.PrivateKey.PrivateExponent, kp.PrivateKey.P, kp.PrivateKey.Q));

            return(new PgpKeyPair(pubKey, privKey));
        }
Example #25
0
        private void Generate()
        {
            SecureRandom random = SecureRandom.GetInstance("SHA1PRNG");

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

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

            AsymmetricCipherKeyPair kpSign = keyGen.GenerateKeyPair();

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

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

            AsymmetricCipherKeyPair kpEnc = keyGen.GenerateKeyPair();

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

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

            keyRingGen.AddSubKey(ecdhKeyPair);

            PgpPublicKeyRing pubRing = keyRingGen.GeneratePublicKeyRing();

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

            PgpSecretKeyRing secRing = keyRingGen.GenerateSecretKeyRing();

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

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

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

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

            PgpPrivateKey pgpPrivKey = secRing.GetSecretKey().ExtractPrivateKey(passPhrase);
        }
Example #26
0
        public string DecryptKeycode(string privateKeyStr, string encryptedKeycode)
        {
            var rawMessage = Encoding.ASCII.GetBytes(encryptedKeycode);

            Stream inputStream = new MemoryStream(rawMessage);

            inputStream = PgpUtilities.GetDecoderStream(inputStream);

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

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

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

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

            PgpPublicKeyEncryptedData dataObject = null;

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

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

            var dataStream = dataObject.GetDataStream(key);

            var pgpFact = new PgpObjectFactory(dataStream);

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

            var unc = ld.GetInputStream();

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

            return(keycode);
        }
Example #27
0
        private PgpPrivateKey ReadPrivateKey(string password)
        {
            PgpPrivateKey privateKey = SecretKey.ExtractPrivateKey(password.ToCharArray());

            if (privateKey != null)
            {
                return(privateKey);
            }
            throw new ArgumentException("No PGP Key Found");
        }
        private PgpPrivateKey ReadPrivateKey(string passPhrase)
        {
            PgpPrivateKey privateKey = SecretKey.ExtractPrivateKey(passPhrase.ToCharArray());

            if (privateKey != null)
            {
                return(privateKey);
            }
            throw new ArgumentException("No private key found in secret key.");
        }
Example #29
0
        public string Decrypt(string inputData)
        {
            PgpPrivateKey privateKey = this.privateKey;

            var pgpData = System.Text.Encoding.ASCII.GetBytes(inputData);

            byte[] decryptedData = Decrypt(pgpData, privateKey);

            return(System.Text.Encoding.ASCII.GetString(decryptedData));
        }
Example #30
0
        private void doTestSigV3(
            PublicKeyAlgorithmTag encAlgorithm,
            HashAlgorithmTag hashAlgorithm,
            PgpPublicKey pubKey,
            PgpPrivateKey privKey)
        {
            byte[] bytes = generateV3BinarySig(privKey, encAlgorithm, hashAlgorithm);

            verifySignature(bytes, hashAlgorithm, pubKey, TEST_DATA);
        }
Example #31
0
		/**
        * Generated signature test
        *
        * @param sKey
        * @param pgpPrivKey
        * @return test result
        */
        public void GenerateTest(
            PgpSecretKeyRing sKey,
            PgpPublicKey     pgpPubKey,
            PgpPrivateKey    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");
            }
        }
Example #32
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);
            }
        }
Example #33
0
        private void MixedTest(
            PgpPrivateKey	pgpPrivKey,
            PgpPublicKey	pgpPubKey)
        {
            byte[] text = Encoding.ASCII.GetBytes("hello world!\n");

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

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

            lGen.Close();

            byte[] bytes = bOut.ToArray();

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

            MemoryStream bcOut = new MemoryStream();

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

            encGen.AddMethod(pgpPubKey);

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

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

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

            cOut.Close();

            byte[] encData = bcOut.ToArray();

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

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

            PgpPublicKeyEncryptedData  encP = (PgpPublicKeyEncryptedData)encList[0];

            Stream clear = encP.GetDataStream(pgpPrivKey);

            PgpObjectFactory pgpFact = new PgpObjectFactory(clear);

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

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

            encList = (PgpEncryptedDataList)pgpF.NextPgpObject();

            PgpPbeEncryptedData encPbe = (PgpPbeEncryptedData) encList[1];

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

            pgpF = new PgpObjectFactory(clear);

            CheckLiteralData((PgpLiteralData) pgpF.NextPgpObject(), text);
        }
Example #34
0
		private void doTestSigV3(
			PublicKeyAlgorithmTag	encAlgorithm,
			HashAlgorithmTag		hashAlgorithm,
			PgpPublicKey			pubKey,
			PgpPrivateKey			privKey)
		{
			byte[] bytes = generateV3BinarySig(privKey, encAlgorithm, hashAlgorithm);

			verifySignature(bytes, hashAlgorithm, pubKey, TEST_DATA);
		}
Example #35
0
		private byte[] generateV3BinarySig(
			PgpPrivateKey			privKey,
			PublicKeyAlgorithmTag	encAlgorithm,
			HashAlgorithmTag		hashAlgorithm)
		{
			MemoryStream bOut = new MemoryStream();
			MemoryStream testIn = new MemoryStream(TEST_DATA, false);
			PgpV3SignatureGenerator sGen = new PgpV3SignatureGenerator(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);

			return bOut.ToArray();
		}
Example #36
0
		private void doTestTextSigV3(
			PublicKeyAlgorithmTag	encAlgorithm,
			HashAlgorithmTag		hashAlgorithm,
			PgpPublicKey			pubKey,
			PgpPrivateKey			privKey,
			byte[]					data,
			byte[]					canonicalData)
		{
			PgpV3SignatureGenerator sGen = new PgpV3SignatureGenerator(encAlgorithm, HashAlgorithmTag.Sha1);
			MemoryStream bOut = new MemoryStream();
			MemoryStream testIn = new MemoryStream(data, false);

			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,
				DateTime.UtcNow);

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

			sig.Encode(bOut);

			verifySignature(bOut.ToArray(), hashAlgorithm, pubKey, canonicalData);
		}