/// <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;
        }
Esempio n. 2
0
        /// <summary>
        /// Parses a single packet out of the given binary
        /// data. Even if there are more than one packets in the byte
        /// array, only the first packet is returned.
        /// </summary>
        /// <param name="bBinaryData">A byte array containing a set
        /// of OpenPGP packets</param>
        /// <returns>Returns an single OpenPGP packets</returns>
        /// <remarks>No remarks</remarks>
        public virtual Packet ParsePacket(byte[] bBinaryData)
        {
            Packet pReturnPacket = new Packet();

            if ((bBinaryData[0] & 0xC0) == 0xC0)
            {
                pfFormat = PacketFormats.New;
            }
            else if ((bBinaryData[0] & 0xC0) == 0x80)
            {
                pfFormat = PacketFormats.Old;
            }
            else
            {
                throw(new ArgumentException("This is not a valid OpenPGP Packet"));
            }


            if (pfFormat == PacketFormats.New)
            {
                int iBinaryDataPos = 1;
                ctContent = (ContentTypes)(bBinaryData[0] & 0x3F);
                lLength   = bBinaryData[1];
                bBody     = new byte[0];
                int iHeaderLength = 1;
                //partial body lengths
                while ((lLength > 223) && (lLength < 255))
                {
                    iBinaryDataPos += 1;
                    iHeaderLength++;
                    int lPartialBody = 1 << ((int)(lLength & 0x1F));
                    int lOldLength   = 0;
                    if (bBody.Length > 0)
                    {
                        byte[] bOldBody = new byte[bBody.Length];
                        bBody.CopyTo(bOldBody, 0);
                        bBody = new byte[bOldBody.Length + lPartialBody];
                        bOldBody.CopyTo(bBody, 0);
                        lOldLength = bBody.Length;
                    }
                    else
                    {
                        bBody = new byte[lPartialBody];
                    }
                    Array.Copy(bBinaryData, iBinaryDataPos, bBody, bBody.Length - lPartialBody, lPartialBody);
                    lLength         = bBinaryData[iBinaryDataPos + lPartialBody];
                    iBinaryDataPos += lPartialBody;
                }                 //partial bodies must end with a normal header!
                if (lLength < 192)
                {
                    iHeaderLength++;
                    bHeader = new byte[iHeaderLength];
                    if (bBody.Length == 0)
                    {
                        Array.Copy(bBinaryData, 0, bHeader, 0, 2);
                        iBinaryDataPos = 1;
                    }
                    byte[] bOldBody = new byte[bBody.Length];
                    bBody.CopyTo(bOldBody, 0);
                    bBody = new byte[bOldBody.Length + lLength];
                    bOldBody.CopyTo(bBody, 0);
                    Array.Copy(bBinaryData, iBinaryDataPos + 1, bBody, bBody.Length - (int)lLength, (int)lLength);
                }
                else if ((lLength > 191) && (lLength < 224))
                {
                    iHeaderLength += 2;
                    bHeader        = new byte[iHeaderLength];
                    if (bBody.Length == 0)
                    {
                        Array.Copy(bBinaryData, 0, bHeader, 0, 3);
                        iBinaryDataPos = 1;
                    }
                    lLength = ((bBinaryData[iBinaryDataPos++] - 192) << 8) + bBinaryData[iBinaryDataPos++] + 192;
                    byte[] bOldBody = new byte[bBody.Length];
                    bBody.CopyTo(bOldBody, 0);
                    bBody = new byte[bOldBody.Length + lLength];
                    bOldBody.CopyTo(bBody, 0);
                    Array.Copy(bBinaryData, iBinaryDataPos, bBody, bBody.Length - (int)lLength, (int)lLength);
                }
                else if (lLength == 255)
                {
                    iHeaderLength += 5;
                    bHeader        = new byte[iHeaderLength];
                    if (bBody.Length == 0)
                    {
                        Array.Copy(bBinaryData, 0, bHeader, 0, 6);
                        iBinaryDataPos = 1;
                    }
                    lLength = (bBinaryData[iBinaryDataPos++] << 24) ^ (bBinaryData[iBinaryDataPos++] << 16) ^
                              (bBinaryData[iBinaryDataPos++] << 8) ^ bBinaryData[iBinaryDataPos++];
                    byte[] bOldBody = new byte[bBody.Length];
                    bBody.CopyTo(bOldBody, 0);
                    bBody = new byte[bOldBody.Length + lLength];
                    bOldBody.CopyTo(bBody, 0);
                    Array.Copy(bBinaryData, iBinaryDataPos, bBody, bBody.Length - (int)lLength, (int)lLength);
                }
            }
            else
            {
                ctContent = (ContentTypes)((bBinaryData[0] & 0x3C) >> 2);
                switch (bBinaryData[0] & 0x03)
                {
                case 0:
                    lLength = bBinaryData[1];
                    bHeader = new byte[2];
                    break;

                case 1:
                    lLength = (bBinaryData[1] << 8) ^ (bBinaryData[2]);
                    bHeader = new byte[3];
                    break;

                case 2:
                    lLength = (bBinaryData[1] << 16) ^ (bBinaryData[2] << 8) ^
                              (bBinaryData[3]);
                    bHeader = new byte[4];
                    break;

                case 3:
                    throw new System.NotSupportedException("Packets of indetermined length are not supported due to security considerations!");

                default:
                    throw new System.ApplicationException("This is not a valid Packet!");
                }
                bBody = new byte[lLength];
                Array.Copy(bBinaryData, 0, bHeader, 0, bHeader.Length);
                Array.Copy(bBinaryData, bHeader.Length, bBody, 0, (int)lLength);
            }

            this.bIsUpdated = false;
            switch (ctContent)
            {
            case ContentTypes.AsymSessionKey:
                pReturnPacket = new AsymSessionKeyPacket(this);
                pReturnPacket = pReturnPacket.ParsePacket(bBody);
                break;

            case ContentTypes.Compressed:
                pReturnPacket = new CompressedDataPacket(this);
                pReturnPacket = pReturnPacket.ParsePacket(bBody);
                break;

            case ContentTypes.LiteralData:
                pReturnPacket = new LiteralDataPacket(this);
                pReturnPacket = pReturnPacket.ParsePacket(bBody);
                break;

            case ContentTypes.Marker:
                pReturnPacket = new Packet(this);
                //We can savly ignore Marker packets!
                //MessageBox.Show("This is a marker packet. It is not yet supported.");
                break;

            case ContentTypes.OnePassSignature:
                pReturnPacket = new OnePassSignaturePacket(this);
                //System.Windows.Forms.MessageBox.Show("This is a One Pass Signature Packet. It is not yet supported");
                break;

            //Content is Public Key Packet
            case ContentTypes.PublicKey:
                pReturnPacket = new PublicKeyPacket(this);
                pReturnPacket = pReturnPacket.ParsePacket(bBody);
                break;

            //Content is Public Subkey Packet. Same format as Public Key Packet
            case ContentTypes.PublicSubkey:
                pReturnPacket = new PublicKeyPacket(this);
                pReturnPacket = pReturnPacket.ParsePacket(bBody);
                break;

            case ContentTypes.SecretKey:
                pReturnPacket = new SecretKeyPacket(this);
                pReturnPacket = pReturnPacket.ParsePacket(bBody);
                break;

            case ContentTypes.SecretSubkey:
                pReturnPacket = new SecretKeyPacket(this);
                pReturnPacket = pReturnPacket.ParsePacket(bBody);
                break;

            case ContentTypes.Signature:
                pReturnPacket = new SignaturePacket(this);
                pReturnPacket = pReturnPacket.ParsePacket(bBody);
                break;

            case ContentTypes.SymEncrypted:
                pReturnPacket = new SymmetricallyEncryptedDataPacket(this);
                pReturnPacket = pReturnPacket.ParsePacket(bBody);
                break;

            case ContentTypes.SymSessionKey:
                pReturnPacket = new SymSessionKeyPacket(this);
                pReturnPacket = pReturnPacket.ParsePacket(bBody);
                break;

            case ContentTypes.Trust:
                pReturnPacket = new Packet(this);
                //throw new Exception("This is a Trust Packet. It is not yet supported");
                break;

            case ContentTypes.UserID:
                pReturnPacket = new UserIDPacket(this);
                pReturnPacket = pReturnPacket.ParsePacket(bBody);
                break;

            default:
                pReturnPacket = new Packet(this);
                //throw new Exception("Sorry, but this is a packet I don't know about!");
                break;
            }

            pReturnPacket.bIsUpdated = false;
            return(pReturnPacket);
        }
        /// <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);
                }
            }
        }
Esempio n. 4
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;
        }
Esempio n. 5
0
        /// <summary>
        /// Parses a single packet out of the given binary
        /// data. Even if there are more than one packets in the byte
        /// array, only the first packet is returned.
        /// </summary>
        /// <param name="bBinaryData">A byte array containing a set
        /// of OpenPGP packets</param>
        /// <returns>Returns an single OpenPGP packets</returns>
        /// <remarks>No remarks</remarks>
        public virtual Packet ParsePacket(byte[] bBinaryData)
        {
            Packet pReturnPacket = new Packet();

            if ((bBinaryData[0] & 0xC0) == 0xC0) {
                pfFormat = PacketFormats.New;
            } else if ((bBinaryData[0] & 0xC0) == 0x80) {
                pfFormat = PacketFormats.Old;
            } else {
                throw(new ArgumentException("This is not a valid OpenPGP Packet"));
            }

            if (pfFormat == PacketFormats.New) {
                int iBinaryDataPos = 1;
                ctContent = (ContentTypes)(bBinaryData[0] & 0x3F);
                lLength = bBinaryData[1];
                bBody = new byte[0];
                int iHeaderLength = 1;
                //partial body lengths
                while ((lLength > 223) && (lLength < 255)) {
                    iBinaryDataPos += 1;
                    iHeaderLength++;
                    int lPartialBody = 1 << ((int)(lLength & 0x1F));
                    int lOldLength = 0;
                    if (bBody.Length > 0) {
                        byte[] bOldBody = new byte[bBody.Length];
                        bBody.CopyTo(bOldBody, 0);
                        bBody = new byte[bOldBody.Length + lPartialBody];
                        bOldBody.CopyTo(bBody, 0);
                        lOldLength = bBody.Length;
                    } else {
                        bBody = new byte[lPartialBody];
                    }
                    Array.Copy(bBinaryData, iBinaryDataPos, bBody, bBody.Length - lPartialBody, lPartialBody);
                    lLength = bBinaryData[iBinaryDataPos + lPartialBody];
                    iBinaryDataPos += lPartialBody;
                } //partial bodies must end with a normal header!
                if (lLength < 192) {
                    iHeaderLength++;
                    bHeader = new byte[iHeaderLength];
                    if (bBody.Length == 0) {
                        Array.Copy(bBinaryData, 0, bHeader, 0, 2);
                        iBinaryDataPos = 1;
                    }
                    byte[] bOldBody = new byte[bBody.Length];
                    bBody.CopyTo(bOldBody, 0);
                    bBody = new byte[bOldBody.Length + lLength];
                    bOldBody.CopyTo(bBody, 0);
                    Array.Copy(bBinaryData, iBinaryDataPos + 1, bBody, bBody.Length - (int)lLength, (int)lLength);
                } else if ((lLength > 191) && (lLength < 224)) {
                    iHeaderLength += 2;
                    bHeader = new byte[iHeaderLength];
                    if (bBody.Length == 0) {
                        Array.Copy(bBinaryData, 0, bHeader, 0, 3);
                        iBinaryDataPos = 1;
                    }
                    lLength = ((bBinaryData[iBinaryDataPos++] - 192) << 8) + bBinaryData[iBinaryDataPos++] + 192;
                    byte[] bOldBody = new byte[bBody.Length];
                    bBody.CopyTo(bOldBody, 0);
                    bBody = new byte[bOldBody.Length + lLength];
                    bOldBody.CopyTo(bBody, 0);
                    Array.Copy(bBinaryData, iBinaryDataPos, bBody, bBody.Length - (int)lLength, (int)lLength);
                } else if (lLength == 255) {
                    iHeaderLength += 5;
                    bHeader = new byte[iHeaderLength];
                    if (bBody.Length == 0) {
                        Array.Copy(bBinaryData, 0, bHeader, 0, 6);
                        iBinaryDataPos = 1;
                    }
                    lLength = (bBinaryData[iBinaryDataPos++] << 24) ^ (bBinaryData[iBinaryDataPos++] << 16) ^
                              (bBinaryData[iBinaryDataPos++] << 8) ^ bBinaryData[iBinaryDataPos++];
                    byte[] bOldBody = new byte[bBody.Length];
                    bBody.CopyTo(bOldBody, 0);
                    bBody = new byte[bOldBody.Length + lLength];
                    bOldBody.CopyTo(bBody, 0);
                    Array.Copy(bBinaryData, iBinaryDataPos, bBody, bBody.Length - (int)lLength, (int)lLength);
                }

            } else {
                ctContent = (ContentTypes)((bBinaryData[0] & 0x3C) >> 2);
                switch (bBinaryData[0] & 0x03) {
                    case 0:
                        lLength = bBinaryData[1];
                        bHeader = new byte[2];
                        break;
                    case 1:
                        lLength = (bBinaryData[1] << 8) ^ (bBinaryData[2]);
                        bHeader = new byte[3];
                        break;
                    case 2:
                        lLength = (bBinaryData[1] << 16) ^ (bBinaryData[2] << 8) ^
                                  (bBinaryData[3]);
                        bHeader = new byte[4];
                        break;
                    case 3:
                        throw new System.NotSupportedException("Packets of indetermined length are not supported due to security considerations!");
                    default:
                        throw new System.ApplicationException("This is not a valid Packet!");
                }
                bBody = new byte[lLength];
                Array.Copy(bBinaryData, 0, bHeader, 0, bHeader.Length);
                Array.Copy(bBinaryData, bHeader.Length, bBody, 0, (int)lLength);
            }

            this.bIsUpdated = false;
            switch (ctContent) {
                case ContentTypes.AsymSessionKey:
                    pReturnPacket = new AsymSessionKeyPacket(this);
                    pReturnPacket = pReturnPacket.ParsePacket(bBody);
                    break;
                case ContentTypes.Compressed:
                    pReturnPacket = new CompressedDataPacket(this);
                    pReturnPacket = pReturnPacket.ParsePacket(bBody);
                    break;
                case ContentTypes.LiteralData:
                    pReturnPacket = new LiteralDataPacket(this);
                    pReturnPacket = pReturnPacket.ParsePacket(bBody);
                    break;
                case ContentTypes.Marker:
                    pReturnPacket = new Packet(this);
                    //We can savly ignore Marker packets!
                    //MessageBox.Show("This is a marker packet. It is not yet supported.");
                    break;
                case ContentTypes.OnePassSignature:
                    pReturnPacket = new OnePassSignaturePacket(this);
                    //System.Windows.Forms.MessageBox.Show("This is a One Pass Signature Packet. It is not yet supported");
                    break;
                //Content is Public Key Packet
                case ContentTypes.PublicKey:
                    pReturnPacket = new PublicKeyPacket(this);
                    pReturnPacket = pReturnPacket.ParsePacket(bBody);
                    break;
                //Content is Public Subkey Packet. Same format as Public Key Packet
                case ContentTypes.PublicSubkey:
                    pReturnPacket = new PublicKeyPacket(this);
                    pReturnPacket = pReturnPacket.ParsePacket(bBody);
                    break;
                case ContentTypes.SecretKey:
                    pReturnPacket = new SecretKeyPacket(this);
                    pReturnPacket = pReturnPacket.ParsePacket(bBody);
                    break;
                case ContentTypes.SecretSubkey:
                    pReturnPacket = new SecretKeyPacket(this);
                    pReturnPacket = pReturnPacket.ParsePacket(bBody);
                    break;
                case ContentTypes.Signature:
                    pReturnPacket = new SignaturePacket(this);
                    pReturnPacket = pReturnPacket.ParsePacket(bBody);
                    break;
                case ContentTypes.SymEncrypted:
                    pReturnPacket = new SymmetricallyEncryptedDataPacket(this);
                    pReturnPacket = pReturnPacket.ParsePacket(bBody);
                    break;
                case ContentTypes.SymSessionKey:
                    pReturnPacket = new SymSessionKeyPacket(this);
                    pReturnPacket = pReturnPacket.ParsePacket(bBody);
                    break;
                case ContentTypes.Trust:
                    pReturnPacket = new Packet(this);
                    //throw new Exception("This is a Trust Packet. It is not yet supported");
                    break;
                case ContentTypes.UserID:
                    pReturnPacket = new UserIDPacket(this);
                    pReturnPacket = pReturnPacket.ParsePacket(bBody);
                    break;
                default:
                    pReturnPacket = new Packet(this);
                    //throw new Exception("Sorry, but this is a packet I don't know about!");
                    break;
            }

            pReturnPacket.bIsUpdated = false;
            return pReturnPacket;
        }
Esempio n. 6
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;
        }
Esempio n. 7
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();
        }