コード例 #1
0
        /// <summary>
        /// Decrypts the encrypted message if it is a symmetrically encrypted
        /// message with the passphrase given as argument.
        /// </summary>
        /// <param name="strPassphrase">The passphrase that was used to encrypt
        /// the message</param>
        /// <returns>Returns the message that was encrypted. Usually this is
        /// an compressed or literal message.</returns>
        /// <remarks>No remarks</remarks>
        public Message Decrypt(string strPassphrase)
        {
            if (esKeys.SymKeys.Count == 0)
            {
                throw new Exception("This message is not symmetrically encrypted. Please provide a keyring rather than a passphrase!");
            }

            Packet[] pContent = new Packet[0];
            Packet[] pReturn  = new Packet[0];

            IEnumerator ieKeys = esKeys.SymKeys.GetEnumerator();

            while (ieKeys.MoveNext())
            {
                SymSessionKeyPacket skpKey = (SymSessionKeyPacket)ieKeys.Current;
                byte[] key = skpKey.S2KSpecifier.GetKey(strPassphrase, CipherHelper.CipherKeySize(skpKey.Algorithm));

                try {
                    SymmetricAlgorithm saAlgo = CipherHelper.CreateSymAlgorithm(skpKey.Algorithm);
                    pContent = sepData.Decrypt(key, saAlgo);
                } catch (System.Security.Cryptography.CryptographicException) {}
                if (pContent.Length > 0)
                {
                    pReturn = pContent;
                }
            }

            if (pReturn.Length == 0)
            {
                throw new System.Security.Cryptography.CryptographicException("Wrong passphrase!");
            }

            // now we need to look what kind of message was hidden in the
            // encrypted data

            // it can be either a literal message
            LiteralMessage lmLiteral = new LiteralMessage();

            try {
                int iPos = lmLiteral.ParseMessage(pReturn);
                return(lmLiteral);
            } catch (Exception) {}

            // or an compressed Message
            CompressedMessage cmCompressed = new CompressedMessage();

            try {
                int iPos = cmCompressed.ParseMessage(pReturn);
                return(cmCompressed);
            } catch (Exception) {}

            throw new System.ArgumentException("Encrypted package content is not a valid message!");
        }
コード例 #2
0
        /// <summary>
        /// Method handling encryption/signing
        /// </summary>
        /// <param name="strMessage">text to be encrypted</param>
        /// <param name="tskKey">secret key needed for encyption purpose</param>
        /// <param name="tpkKeys">public key needed for signing purpose</param>
        /// <param name="bSign">sign text?</param>
        /// <param name="strPassphrase">passphrase for the secret key</param>
        /// <returns>the encrypted text</returns>
        public string EncryptText(string strMessage, TransportableSecretKey tskKey, ArrayList tpkKeys,  bool bSign, string strPassphrase)
        {
            if(this.pkrPublicKeyRing == null || this.skrSecretKeyRing == null) {
                throw new Exception("<ERROR code=\"5\">");
            }

            if(bSign && tskKey == null) {
                throw new Exception("Need a Private Key To Sign!");
            }

            LiteralMessage lmMessage = new LiteralMessage(DataFormatTypes.Text);
            lmMessage.Text = strMessage;
            lmMessage.TimeCreated = DateTime.Now;
            lmMessage.Filename = "";

            SharpPrivacy.SharpPrivacyLib.OpenPGP.Messages.Message mEncryptionMessage = lmMessage;

            if (bSign) {
                SignedMessage smMessage = new SignedMessage();
                smMessage.MessageSigned = lmMessage;
                SignaturePacket spPacket = new SignaturePacket();
                spPacket.Version = SignaturePacketVersionNumbers.v3;
                SecretKeyPacket skpKey = tskKey.FindKey(AsymActions.Sign);
                spPacket.KeyID = skpKey.PublicKey.KeyID;
                spPacket.HashAlgorithm = HashAlgorithms.SHA1;
                spPacket.SignatureAlgorithm = skpKey.PublicKey.Algorithm;
                spPacket.TimeCreated = DateTime.Now;
                spPacket.SignatureType = SignatureTypes.TextSignature;
                spPacket.Sign(lmMessage.Binary, skpKey, strPassphrase);
                smMessage.Signature = spPacket;
                mEncryptionMessage = smMessage;
            }

            CompressedMessage cmMessage = new CompressedMessage();
            cmMessage.Compress(mEncryptionMessage);

            SymAlgorithms saAlgo = GetSymAlgorithmPreferences(tpkKeys);

            SymmetricallyEncryptedDataPacket sedpEncrypted = new SymmetricallyEncryptedDataPacket();
            SymmetricAlgorithm saEncrypt = CipherHelper.CreateSymAlgorithm(saAlgo);
            saEncrypt.Mode = CipherMode.OpenPGP_CFB;
            saEncrypt.GenerateKey();
            byte[] bKey = saEncrypt.Key;

            ESKSequence esksKeys = new ESKSequence();
            try {
                esksKeys = CreateESKSequence(tpkKeys, AsymActions.Encrypt, saAlgo, bKey);
            } catch (Exception e) {
                throw new Exception("The following error occured: " + e.Message);
            }

            ICryptoTransform ictEncryptor = saEncrypt.CreateEncryptor();
            byte[] bMessage = cmMessage.GetEncoded();
            byte[] bOutput = new byte[bMessage.Length];
            ictEncryptor.TransformBlock(bMessage, 0, bMessage.Length, ref bOutput, 0);
            bKey.Initialize();

            int iOutLength = (saEncrypt.BlockSize >> 3) + 2 + bMessage.Length;
            sedpEncrypted.Body = new byte[iOutLength];
            Array.Copy(bOutput, 0, sedpEncrypted.Body, 0, iOutLength);

            byte[] bESK = esksKeys.GetEncoded();
            byte[] bEncrypted = sedpEncrypted.Generate();

            byte[] bReturn = new byte[bESK.Length + bEncrypted.Length];
            bESK.CopyTo(bReturn, 0);
            bEncrypted.CopyTo(bReturn, bESK.Length);

            string strReturn = Radix64.Encode(bReturn, true);

            strReturn = Armor.WrapMessage(strReturn);

            return strReturn;
        }
コード例 #3
0
        /// <summary>
        /// Methond handling encryption/signing
        /// </summary>
        /// <param name="strFiles">file list to be encrypted</param>
        /// <param name="tskKey">secret key needed for encyption purpose</param>
        /// <param name="tpkKeys">public key needed for signing purpose</param>
        /// <param name="strPassphrase">passphrase for secret key</param>
        /// <param name="bEncrypt">encrypt files?</param>
        /// <param name="bSign">sign files?</param>
        public void EncryptFiles(String[] strFiles, TransportableSecretKey tskKey, ArrayList tpkKeys, string strPassphrase, bool bEncrypt, bool bSign, bool embedMsg)
        {
            if(this.pkrPublicKeyRing == null || this.skrSecretKeyRing == null) {
                throw new Exception("<ERROR code=\"5\">");
            }

            if (bSign && tskKey == null) {
                throw new Exception("Need a Private Key To Sign!");
            }

            if (bEncrypt && (tpkKeys == null || tpkKeys.Count < 1)) {
                throw new Exception("Need Public Keys To Encrypt!");
            }

            for (int i=0; i<strFiles.Length; i++) {
                byte[] bFileContent = new byte[0];
                try {
                    System.IO.FileStream fsFile = new FileStream(strFiles[i], FileMode.Open);
                    BinaryReader brReader = new BinaryReader(fsFile);
                    bFileContent = brReader.ReadBytes((int)fsFile.Length);
                    brReader.Close();
                    fsFile.Close();
                } catch (Exception e) {
                    throw new Exception("An error occured while opening the file " + strFiles[i] + ": " + e.Message);
                }

                LiteralMessage lmMessage = new LiteralMessage(DataFormatTypes.Binary);
                lmMessage.Binary = bFileContent;
                lmMessage.TimeCreated = DateTime.Now;
                int iLastBackslash = strFiles[i].LastIndexOf("\\");
                lmMessage.Filename = strFiles[i].Substring(iLastBackslash + 1, strFiles[i].Length - iLastBackslash - 1);

                SharpPrivacy.SharpPrivacyLib.OpenPGP.Messages.Message mEncryptionMessage = lmMessage;

                if (bSign) {
                    SignedMessage smMessage = new SignedMessage();
                    smMessage.MessageSigned = lmMessage;
                    SignaturePacket spPacket = new SignaturePacket();
                    spPacket.Version = SignaturePacketVersionNumbers.v3;
                    SecretKeyPacket skpKey = tskKey.FindKey(AsymActions.Sign);
                    spPacket.KeyID = skpKey.PublicKey.KeyID;
                    spPacket.HashAlgorithm = HashAlgorithms.SHA1;
                    spPacket.SignatureAlgorithm = skpKey.PublicKey.Algorithm;
                    spPacket.TimeCreated = DateTime.Now;
                    spPacket.SignatureType = SignatureTypes.TextSignature;
                    spPacket.Sign(lmMessage.Binary, skpKey, strPassphrase);
                    smMessage.Signature = spPacket;
                    mEncryptionMessage = smMessage;
                }

                CompressedMessage cmMessage = new CompressedMessage();
                cmMessage.Compress(mEncryptionMessage);

                byte[] bReturn = new byte[0];
                if (bEncrypt) {
                    SymAlgorithms saAlgo = GetSymAlgorithmPreferences(tpkKeys);
                    SymmetricallyEncryptedDataPacket sedpEncrypted = new SymmetricallyEncryptedDataPacket();
                    SymmetricAlgorithm saEncrypt = CipherHelper.CreateSymAlgorithm(saAlgo);
                    saEncrypt.Mode = CipherMode.OpenPGP_CFB;
                    saEncrypt.GenerateKey();
                    byte[] bKey = saEncrypt.Key;

                    ESKSequence esksKeys = new ESKSequence();
                    try {
                        esksKeys = CreateESKSequence(tpkKeys, AsymActions.Encrypt, saAlgo, bKey);
                    } catch (Exception e) {
                        throw new Exception("The following error occured: " + e.Message);
                    }

                    ICryptoTransform ictEncryptor = saEncrypt.CreateEncryptor();
                    byte[] bMessage = cmMessage.GetEncoded();
                    byte[] bOutput = new byte[bMessage.Length];
                    ictEncryptor.TransformBlock(bMessage, 0, bMessage.Length, ref bOutput, 0);
                    bKey.Initialize();

                    int iOutLength = (saEncrypt.BlockSize >> 3) + 2 + bMessage.Length;
                    sedpEncrypted.Body = new byte[iOutLength];
                    Array.Copy(bOutput, 0, sedpEncrypted.Body, 0, iOutLength);

                    byte[] bESK = esksKeys.GetEncoded();
                    byte[] bEncrypted = sedpEncrypted.Generate();

                    bReturn = new byte[bESK.Length + bEncrypted.Length];
                    bESK.CopyTo(bReturn, 0);
                    bEncrypted.CopyTo(bReturn, bESK.Length);
                } else {
                    if(embedMsg) {
                        bReturn = cmMessage.GetEncoded();
                    } else {
                        byte[] bSignature = ((SignedMessage)mEncryptionMessage).Signature.Generate();
                        string strSignature = Radix64.Encode(bSignature, true);
                        string strFinal = Armor.WrapCleartextSignature(strSignature);
                        try {
                            FileStream fsOut = new FileStream(strFiles[i] + ".asc", FileMode.Create);
                            StreamWriter bwWrite = new StreamWriter(fsOut);

                            bwWrite.Write(strFinal);
                            bwWrite.Close();
                            fsOut.Close();
                            return;
                        } catch (IOException io) {
                            throw new Exception("Could not write to file. The following error occured: " + io.Message);
                        }
                    }
                }

                try {
                    FileStream fsOut = new FileStream(strFiles[i] + ".asc", FileMode.Create);
                    BinaryWriter bwWrite = new BinaryWriter(fsOut);

                    bwWrite.Write(bReturn);
                    bwWrite.Close();
                    fsOut.Close();
                } catch (IOException io) {
                    throw new Exception("Could not write to file. The following error occured: " + io.Message);
                }
            }
        }
コード例 #4
0
        /// <summary>
        /// Method handling decrypting and verifying
        /// </summary>
        /// <param name="bData">data to be decrypted</param>
        /// <param name="strPassphrase">passphrase</param>
        /// <param name="fileOut">the decrypted file location if one produced</param>
        /// <returns>verifying process result</returns>
        private string DecryptAndVerify(byte[] bData, string strPassphrase, string fileOut)
        {
            string strMessage = System.Text.Encoding.UTF8.GetString(bData);
            ArmorTypes atType = new ArmorTypes();
            string strRest = "";
            string strRadix64 = Armor.RemoveArmor(strMessage, ref atType, ref strRest);
            if (strRadix64.Length > 0)
                bData = Radix64.Decode(strRadix64);

            SharpPrivacy.SharpPrivacyLib.OpenPGP.Messages.Message mContent = null;

            if (atType == ArmorTypes.OpenPGPSignedMessage) {
                string strSignature = "";
                string strSignedMessage = Armor.RemoveClearSignatureArmor(strMessage, ref atType, ref strSignature);

                strSignedMessage = Radix64.DashUnescape(strSignedMessage);
                strSignedMessage = Radix64.TrimMessage(strSignedMessage);
                SignedMessage smMessage = new SignedMessage();
                Packet[] pPackets;

                pPackets = Packet.ParsePackets(strSignature);

                if (!(pPackets[0] is SignaturePacket)) {
                    throw new Exception("Not a valid cleartext signature!");
                }
                smMessage.Signature = (SignaturePacket)pPackets[0];

                LiteralMessage lmMessage = new LiteralMessage(DataFormatTypes.Text);
                lmMessage.Text = strSignedMessage;
                smMessage.MessageSigned = lmMessage;

                mContent = smMessage;
            } else {

                // let us see what kind of message this is
                EncryptedMessage emMessage = new EncryptedMessage();
                Packet[] pPackets;
                try {
                    pPackets = Packet.ParsePackets(bData);
                    try {
                        emMessage.ParseMessage(pPackets);

                        if (emMessage.SymmetricallyEncrypted) {
                            // Query passphrase for symmetrically encrypted message

                            mContent = emMessage.Decrypt(strPassphrase);

                        } else {
                            ulong lKeyID = emMessage.GetFittingKeyID(skrSecretKeyRing);
                            mContent = emMessage.Decrypt(skrSecretKeyRing, strPassphrase);
                        }
                    } catch (Exception) {
                        mContent = new CompressedMessage();
                        mContent.ParseMessage(pPackets);
                    }

                    while ((!(mContent is LiteralMessage)) && (!(mContent is SignedMessage))) {
                        if (mContent is CompressedMessage) {
                            mContent = ((CompressedMessage)mContent).Uncompress();
                        } else {
                            throw new Exception("This is not a valid OpenPGP message!");
                        }
                    }
                } catch (Exception ee) {
                    throw new Exception("There was an error decrypting your message: " + ee.Message);
                }
            }

            LiteralMessage lmContent = new LiteralMessage();
            string strDisplay = "";
            if (mContent is SignedMessage) {
                SignedMessage smContent = (SignedMessage)mContent;
                lmContent = smContent.MessageSigned;
                strDisplay += "*** OpenPGP Signed Message ***\r\n";
                strDisplay += "*** Signature Status: " + smContent.Verify(pkrPublicKeyRing) + " ***\r\n";
                strDisplay += "*** Signing Key Dec: " + smContent.Signature.KeyID.ToString() + " ***\r\n";
                strDisplay += "*** Signing Key Hex: " + smContent.Signature.KeyID.ToString("x") + " ***\r\n";
                try {
                    try {
                        strDisplay += "*** Signing Key Expiration: " + pkrPublicKeyRing.Find(smContent.Signature.KeyID,true).KeyExpirationTime + " ***\r\n";
                    } catch(Exception e) {
                        if(e.Message.Equals("never"))
                            strDisplay += "*** Signing Key Expiration: "+e.Message+" ***\r\n";
                        else
                            throw new Exception("Signing_Key_Not_Available");

                    }
                    try {
                        strDisplay += "*** Signing Key Revoked: "+ this.pkrPublicKeyRing.isRevoked(smContent.Signature.KeyID) +" ***\r\n";
                    } catch(Exception e) {
                        string msg = e.Message;
                        strDisplay += "*** Signing Key Revoked: Revocation_Key_Not_Available ***\r\n";
                    }
                } catch (Exception e) {
                    string warn = e.Message;
                    strDisplay += "*** Signing Key Expiration: " + SignatureStatusTypes.Signing_Key_Not_Available + " ***\r\n";
                }
                strDisplay += "*** Signing Date: " + smContent.Signature.TimeCreated.ToString() + "***\r\n\r\n";
            } else if (mContent is LiteralMessage) {
                lmContent = (LiteralMessage)mContent;
                strDisplay += "*** OpenPGP Encrypted Message ***\r\n\r\n";
            } else {
                throw new Exception("An error occured: Could not find an encrypted or signed message!");
            }

            if (lmContent.DataFormat == DataFormatTypes.Text) {
                strDisplay += lmContent.Text;
                strDisplay += "\r\n\r\n*** End OpenPGP Message ***\r\n";
                if(fileOut != null && fileOut != "") {
                    System.IO.FileStream fsOut = new FileStream(fileOut, FileMode.Create);
                    System.IO.BinaryWriter bwOut = new BinaryWriter(fsOut);
                    bwOut.Write(lmContent.Binary);
                    bwOut.Close();
                    fsOut.Close();
                }
            } else {
                System.IO.FileStream fsOut = new FileStream(fileOut, FileMode.Create);
                System.IO.BinaryWriter bwOut = new BinaryWriter(fsOut);
                bwOut.Write(lmContent.Binary);
                bwOut.Close();
                fsOut.Close();
            }
            return strDisplay;
        }
コード例 #5
0
        /// <summary>
        /// Decrypts the current encrypted message using the secret keys
        /// in skrKeyRing and the given passphrase.
        /// </summary>
        /// <param name="skrKeyRing">The secret keyring containing all the
        /// secret keys know to the sytem.</param>
        /// <param name="strPassphrase">The passphrase that was used to
        /// encrypt the secret key material in the key that decrypts
        /// the message.</param>
        /// <returns>Returns the message that was encrypted. Usually this is
        /// an compressed or literal message.</returns>
        /// <remarks>No remarks</remarks>
        public Message Decrypt(SecretKeyRing skrKeyRing, string strPassphrase)
        {
            TransportableSecretKey tskSecretKey   = new TransportableSecretKey();
            AsymSessionKeyPacket   askpSessionKey = new AsymSessionKeyPacket();
            bool bFound = false;

            // let's see, if we can find a fitting Sessionkey packet
            IEnumerator ieSessionkeys = esKeys.AsymKeys.GetEnumerator();

            while (ieSessionkeys.MoveNext())
            {
                if (!(ieSessionkeys.Current is AsymSessionKeyPacket))
                {
                    throw new Exception("Strange Error!");
                }

                AsymSessionKeyPacket askpKey = (AsymSessionKeyPacket)ieSessionkeys.Current;
                ulong lKeyID = askpKey.KeyID;

                TransportableSecretKey tskKey = skrKeyRing.Find(lKeyID);
                if (tskKey != null)
                {
                    bFound         = true;
                    tskSecretKey   = tskKey;
                    askpSessionKey = askpKey;
                }
            }

            if (!bFound)
            {
                throw new Exception("No fitting secret key was found to decrypt the message!");
            }

            askpSessionKey.DecryptSessionKey(tskSecretKey, strPassphrase);
            byte[] bKey = askpSessionKey.SessionKey;

            Packet[] pContent = new Packet[0];
            try {
                SymmetricAlgorithm saAlgo = CipherHelper.CreateSymAlgorithm(askpSessionKey.SymmetricAlgorithm);
                pContent = sepData.Decrypt(bKey, saAlgo);
            } catch (Exception e) {
                throw new System.Exception("Decryption of the Message failed: " + e.Message);
            }

            // now we need to look what kind of message was hidden in the
            // encrypted data

            // it can be either a literal message
            LiteralMessage lmLiteral = new LiteralMessage();

            try {
                int iPos = lmLiteral.ParseMessage(pContent);
                return(lmLiteral);
            } catch (Exception) {}

            // or an compressed Message
            CompressedMessage cmCompressed = new CompressedMessage();

            try {
                int iPos = cmCompressed.ParseMessage(pContent);
                return(cmCompressed);
            } catch (Exception) {}

            throw new System.ArgumentException("Encrypted package content is not a valid message!");
        }
コード例 #6
0
        private byte[] EncryptMessage(Message mToBeEncrypted, ulong[] lTargetKeyIDs)
        {
            CompressedMessage cmMessage = new CompressedMessage();
            cmMessage.Compress(mToBeEncrypted);

            TransportablePublicKey[] tpkSelectedKeys = new TransportablePublicKey[lTargetKeyIDs.Length];
            for (int i=0; i<lTargetKeyIDs.Length; i++)
                tpkSelectedKeys[i] = pkrKeyRing.Find(lTargetKeyIDs[i], true);

            SymAlgorithms saAlgo = GetSymAlgorithmPreferences(tpkSelectedKeys);

            SymmetricallyEncryptedDataPacket sedpEncrypted = new SymmetricallyEncryptedDataPacket();
            SymmetricAlgorithm saEncrypt = CipherHelper.CreateSymAlgorithm(saAlgo);
            saEncrypt.Mode = CipherMode.OpenPGP_CFB;
            saEncrypt.GenerateKey();
            byte[] bKey = saEncrypt.Key;

            ESKSequence esksKeys = new ESKSequence();
            esksKeys = CreateESKSequence(tpkSelectedKeys, AsymActions.Encrypt, saAlgo, bKey);

            ICryptoTransform ictEncryptor = saEncrypt.CreateEncryptor();
            byte[] bMessage = cmMessage.GetEncoded();
            byte[] bOutput = new byte[bMessage.Length];
            ictEncryptor.TransformBlock(bMessage, 0, bMessage.Length, ref bOutput, 0);
            bKey.Initialize();

            int iOutLength = (saEncrypt.BlockSize >> 3) + 2 + bMessage.Length;
            sedpEncrypted.Body = new byte[iOutLength];
            Array.Copy(bOutput, 0, sedpEncrypted.Body, 0, iOutLength);

            byte[] bESK = esksKeys.GetEncoded();
            byte[] bEncrypted = sedpEncrypted.Generate();

            byte[] bReturn = new byte[bESK.Length + bEncrypted.Length];
            bESK.CopyTo(bReturn, 0);
            bEncrypted.CopyTo(bReturn, bESK.Length);

            return bReturn;
        }
コード例 #7
0
        /// <summary>
        /// Decrypts the encrypted message if it is a symmetrically encrypted 
        /// message with the passphrase given as argument.
        /// </summary>
        /// <param name="strPassphrase">The passphrase that was used to encrypt
        /// the message</param>
        /// <returns>Returns the message that was encrypted. Usually this is
        /// an compressed or literal message.</returns>
        /// <remarks>No remarks</remarks>
        public Message Decrypt(string strPassphrase)
        {
            if (esKeys.SymKeys.Count == 0)
                throw new Exception("This message is not symmetrically encrypted. Please provide a keyring rather than a passphrase!");

            Packet[] pContent = new Packet[0];
            Packet[] pReturn = new Packet[0];

            IEnumerator ieKeys = esKeys.SymKeys.GetEnumerator();
            while (ieKeys.MoveNext()) {
                SymSessionKeyPacket skpKey = (SymSessionKeyPacket)ieKeys.Current;
                byte[] key = skpKey.S2KSpecifier.GetKey(strPassphrase, CipherHelper.CipherKeySize(skpKey.Algorithm));

                try {
                    SymmetricAlgorithm saAlgo = CipherHelper.CreateSymAlgorithm(skpKey.Algorithm);
                    pContent = sepData.Decrypt(key, saAlgo);
                } catch (System.Security.Cryptography.CryptographicException) {}
                if (pContent.Length > 0) {
                    pReturn = pContent;
                }
            }

            if (pReturn.Length == 0)
                throw new System.Security.Cryptography.CryptographicException("Wrong passphrase!");

            // now we need to look what kind of message was hidden in the
            // encrypted data

            // it can be either a literal message
            LiteralMessage lmLiteral = new LiteralMessage();
            try {
                int iPos = lmLiteral.ParseMessage(pReturn);
                return lmLiteral;
            } catch (Exception) {}

            // or an compressed Message
            CompressedMessage cmCompressed = new CompressedMessage();
            try {
                int iPos = cmCompressed.ParseMessage(pReturn);
                return cmCompressed;
            } catch (Exception) {}

            throw new System.ArgumentException("Encrypted package content is not a valid message!");
        }
コード例 #8
0
        /// <summary>
        /// Decrypts the current encrypted message using the secret keys
        /// in skrKeyRing and the given passphrase.
        /// </summary>
        /// <param name="skrKeyRing">The secret keyring containing all the
        /// secret keys know to the sytem.</param>
        /// <param name="strPassphrase">The passphrase that was used to
        /// encrypt the secret key material in the key that decrypts
        /// the message.</param>
        /// <returns>Returns the message that was encrypted. Usually this is
        /// an compressed or literal message.</returns>
        /// <remarks>No remarks</remarks>
        public Message Decrypt(SecretKeyRing skrKeyRing, string strPassphrase)
        {
            TransportableSecretKey tskSecretKey = new TransportableSecretKey();
            AsymSessionKeyPacket askpSessionKey = new AsymSessionKeyPacket();
            bool bFound = false;

            // let's see, if we can find a fitting Sessionkey packet
            IEnumerator ieSessionkeys = esKeys.AsymKeys.GetEnumerator();
            while (ieSessionkeys.MoveNext()) {
                if (!(ieSessionkeys.Current is AsymSessionKeyPacket))
                    throw new Exception("Strange Error!");

                AsymSessionKeyPacket askpKey = (AsymSessionKeyPacket)ieSessionkeys.Current;
                ulong lKeyID = askpKey.KeyID;

                TransportableSecretKey tskKey = skrKeyRing.Find(lKeyID);
                if (tskKey != null) {
                    bFound = true;
                    tskSecretKey = tskKey;
                    askpSessionKey = askpKey;
                }
            }

            if (!bFound)
                throw new Exception("No fitting secret key was found to decrypt the message!");

            askpSessionKey.DecryptSessionKey(tskSecretKey, strPassphrase);
            byte[] bKey = askpSessionKey.SessionKey;

            Packet[] pContent = new Packet[0];
            try {
                SymmetricAlgorithm saAlgo = CipherHelper.CreateSymAlgorithm(askpSessionKey.SymmetricAlgorithm);
                pContent = sepData.Decrypt(bKey, saAlgo);
            } catch (Exception e) {
                throw new System.Exception("Decryption of the Message failed: " + e.Message);
            }

            // now we need to look what kind of message was hidden in the
            // encrypted data

            // it can be either a literal message
            LiteralMessage lmLiteral = new LiteralMessage();
            try {
                int iPos = lmLiteral.ParseMessage(pContent);
                return lmLiteral;
            } catch (Exception) {}

            // or an compressed Message
            CompressedMessage cmCompressed = new CompressedMessage();
            try {
                int iPos = cmCompressed.ParseMessage(pContent);
                return cmCompressed;
            } catch (Exception) {}

            throw new System.ArgumentException("Encrypted package content is not a valid message!");
        }
コード例 #9
0
        public static string EncryptText(string strMessage, PublicKeyRing pkrPublicKeyRing, SecretKeyRing skrSecretKeyRing, bool bSign)
        {
            PublicKeySelector pksSelectKeys = new PublicKeySelector(pkrPublicKeyRing);
            pksSelectKeys.ShowDialog();
            TransportableSecretKey tskKey = new TransportableSecretKey();
            string strPassphrase = "";

            if (bSign) {
                QueryPassphrase qpPassphrase = new QueryPassphrase();
                qpPassphrase.ShowMyDialog(skrSecretKeyRing);
                tskKey = qpPassphrase.SelectedKey;
                strPassphrase = qpPassphrase.Passphrase;
            }

            if (pksSelectKeys.SelectedKeys.Count == 0)
                return strMessage;

            Working wWorking = new Working();
            wWorking.Show();

            LiteralMessage lmMessage = new LiteralMessage(DataFormatTypes.Text);
            lmMessage.Text = strMessage;
            lmMessage.TimeCreated = DateTime.Now;
            lmMessage.Filename = "";

            SharpPrivacy.OpenPGP.Messages.Message mEncryptionMessage = lmMessage;

            if (bSign) {
                SignedMessage smMessage = new SignedMessage();
                smMessage.MessageSigned = lmMessage;
                SignaturePacket spPacket = new SignaturePacket();
                spPacket.Version = SignaturePacketVersionNumbers.v3;
                SecretKeyPacket skpKey = tskKey.FindKey(AsymActions.Sign);
                spPacket.KeyID = skpKey.PublicKey.KeyID;
                spPacket.HashAlgorithm = HashAlgorithms.SHA1;
                spPacket.SignatureAlgorithm = skpKey.PublicKey.Algorithm;
                spPacket.TimeCreated = DateTime.Now;
                spPacket.SignatureType = SignatureTypes.TextSignature;
                spPacket.Sign(lmMessage.Binary, skpKey, strPassphrase);
                smMessage.Signature = spPacket;
                mEncryptionMessage = smMessage;
            }

            CompressedMessage cmMessage = new CompressedMessage();
            cmMessage.Compress(mEncryptionMessage);

            wWorking.Progress(20);

            SymAlgorithms saAlgo = GetSymAlgorithmPreferences(pksSelectKeys.SelectedKeys);

            SymmetricallyEncryptedDataPacket sedpEncrypted = new SymmetricallyEncryptedDataPacket();
            SymmetricAlgorithm saEncrypt = CipherHelper.CreateSymAlgorithm(saAlgo);
            saEncrypt.Mode = CipherMode.OpenPGP_CFB;
            saEncrypt.GenerateKey();
            byte[] bKey = saEncrypt.Key;

            wWorking.Progress(10);
            ESKSequence esksKeys = new ESKSequence();
            try {
                 esksKeys = CreateESKSequence(pksSelectKeys.SelectedKeys, AsymActions.Encrypt, saAlgo, bKey);
            } catch (Exception e) {
                wWorking.Hide();
                MessageBox.Show("The following error occured: " + e.Message, "Error...");
                return strMessage;
            }

            wWorking.Progress(50);

            ICryptoTransform ictEncryptor = saEncrypt.CreateEncryptor();
            byte[] bMessage = cmMessage.GetEncoded();
            byte[] bOutput = new byte[bMessage.Length];
            ictEncryptor.TransformBlock(bMessage, 0, bMessage.Length, ref bOutput, 0);
            bKey.Initialize();

            wWorking.Progress(10);

            int iOutLength = (saEncrypt.BlockSize >> 3) + 2 + bMessage.Length;
            sedpEncrypted.Body = new byte[iOutLength];
            Array.Copy(bOutput, 0, sedpEncrypted.Body, 0, iOutLength);

            byte[] bESK = esksKeys.GetEncoded();
            byte[] bEncrypted = sedpEncrypted.Generate();

            byte[] bReturn = new byte[bESK.Length + bEncrypted.Length];
            bESK.CopyTo(bReturn, 0);
            bEncrypted.CopyTo(bReturn, bESK.Length);

            wWorking.Progress(10);
            string strReturn = Radix64.Encode(bReturn, true);

            strReturn = Armor.WrapMessage(strReturn);

            wWorking.Hide();
            return strReturn;
        }
コード例 #10
0
        public static void EncryptFiles(String[] strFiles, PublicKeyRing pkrPublicKeyRing, SecretKeyRing skrSecretKeyRing, bool bEncrypt, bool bSign)
        {
            PublicKeySelector pksSelectKeys = new PublicKeySelector(pkrPublicKeyRing);
            if (bEncrypt) {
                pksSelectKeys.ShowDialog();
                if (pksSelectKeys.SelectedKeys.Count == 0) {
                    MessageBox.Show("You did not select a public key to encrypt to. Doing nothing...", "Nothing Done...");
                    return;
                }
            }

            TransportableSecretKey tskKey = new TransportableSecretKey();
            string strPassphrase = "";

            if (bSign) {
                QueryPassphrase qpPassphrase = new QueryPassphrase();
                qpPassphrase.ShowMyDialog(skrSecretKeyRing);
                tskKey = qpPassphrase.SelectedKey;
                strPassphrase = qpPassphrase.Passphrase;
            }

            Working wWorking = new Working();
            wWorking.Show();

            for (int i=0; i<strFiles.Length; i++) {
                byte[] bFileContent = new byte[0];
                try {
                    System.IO.FileStream fsFile = new FileStream(strFiles[i], FileMode.Open);
                    BinaryReader brReader = new BinaryReader(fsFile);
                    bFileContent = brReader.ReadBytes((int)fsFile.Length);
                    brReader.Close();
                    fsFile.Close();
                } catch (Exception e) {
                    wWorking.Hide();
                    MessageBox.Show("An error occured while opening the file " + strFiles[i] + ": " + e.Message, "Error...");
                    return;
                }

                LiteralMessage lmMessage = new LiteralMessage(DataFormatTypes.Binary);
                lmMessage.Binary = bFileContent;
                lmMessage.TimeCreated = DateTime.Now;
                int iLastBackslash = strFiles[i].LastIndexOf("\\");
                lmMessage.Filename = strFiles[i].Substring(iLastBackslash + 1, strFiles[i].Length - iLastBackslash - 1);

                SharpPrivacy.OpenPGP.Messages.Message mEncryptionMessage = lmMessage;

                if (bSign) {
                    SignedMessage smMessage = new SignedMessage();
                    smMessage.MessageSigned = lmMessage;
                    SignaturePacket spPacket = new SignaturePacket();
                    spPacket.Version = SignaturePacketVersionNumbers.v3;
                    SecretKeyPacket skpKey = tskKey.FindKey(AsymActions.Sign);
                    spPacket.KeyID = skpKey.PublicKey.KeyID;
                    spPacket.HashAlgorithm = HashAlgorithms.SHA1;
                    spPacket.SignatureAlgorithm = skpKey.PublicKey.Algorithm;
                    spPacket.TimeCreated = DateTime.Now;
                    spPacket.SignatureType = SignatureTypes.TextSignature;
                    spPacket.Sign(lmMessage.Binary, skpKey, strPassphrase);
                    smMessage.Signature = spPacket;
                    mEncryptionMessage = smMessage;
                }

                CompressedMessage cmMessage = new CompressedMessage();
                cmMessage.Compress(mEncryptionMessage);

                wWorking.Progress(20/strFiles.Length);

                SymAlgorithms saAlgo = GetSymAlgorithmPreferences(pksSelectKeys.SelectedKeys);

                wWorking.Progress(10/strFiles.Length);
                byte[] bReturn = new byte[0];
                if (bEncrypt) {
                    SymmetricallyEncryptedDataPacket sedpEncrypted = new SymmetricallyEncryptedDataPacket();
                    SymmetricAlgorithm saEncrypt = CipherHelper.CreateSymAlgorithm(saAlgo);
                    saEncrypt.Mode = CipherMode.OpenPGP_CFB;
                    saEncrypt.GenerateKey();
                    byte[] bKey = saEncrypt.Key;

                    ESKSequence esksKeys = new ESKSequence();
                    try {
                         esksKeys = CreateESKSequence(pksSelectKeys.SelectedKeys, AsymActions.Encrypt, saAlgo, bKey);
                    } catch (Exception e) {
                        wWorking.Hide();
                        MessageBox.Show("The following error occured: " + e.Message, "Error...");
                        return;
                    }

                    wWorking.Progress(50/strFiles.Length);

                    ICryptoTransform ictEncryptor = saEncrypt.CreateEncryptor();
                    byte[] bMessage = cmMessage.GetEncoded();
                    byte[] bOutput = new byte[bMessage.Length];
                    ictEncryptor.TransformBlock(bMessage, 0, bMessage.Length, ref bOutput, 0);
                    bKey.Initialize();

                    wWorking.Progress(10/strFiles.Length);

                    int iOutLength = (saEncrypt.BlockSize >> 3) + 2 + bMessage.Length;
                    sedpEncrypted.Body = new byte[iOutLength];
                    Array.Copy(bOutput, 0, sedpEncrypted.Body, 0, iOutLength);

                    byte[] bESK = esksKeys.GetEncoded();
                    byte[] bEncrypted = sedpEncrypted.Generate();

                    bReturn = new byte[bESK.Length + bEncrypted.Length];
                    bESK.CopyTo(bReturn, 0);
                    bEncrypted.CopyTo(bReturn, bESK.Length);
                } else {
                    wWorking.Progress(60/strFiles.Length);
                    bReturn = cmMessage.GetEncoded();
                }

                wWorking.Progress(10/strFiles.Length);

                try {
                    FileStream fsOut = new FileStream(strFiles[i] + ".asc", FileMode.CreateNew);
                    BinaryWriter bwWrite = new BinaryWriter(fsOut);

                    bwWrite.Write(bReturn);
                    bwWrite.Close();
                    fsOut.Close();
                } catch (IOException io) {
                    MessageBox.Show("Could not write to file. The following error occured: " + io.Message, "Error...");
                }
            }

            wWorking.Hide();
        }