void cmdDecode_Click(Object sender, System.EventArgs e) { byte[] bPlaintext = Radix64.Decode(txtRadix64.Text); string strOutput = ""; for (int i=0; i<bPlaintext.Length; i++) { strOutput += bPlaintext[i].ToString() + ":"; } this.txtPlaintext.Text = strOutput; PublicKeyRing pkpRing = new PublicKeyRing(); pkpRing.Load("C:\\keyring.txt"); pkpRing.Save("C:\\keyringout.txt"); }
/// <summary> /// Verifies the signature of this signed message. /// </summary> /// <remarks>No remarks</remarks> /// <returns>Returns a SignatureStatusType that contains /// whether the signature was valid, invalid or could not be /// verified</returns> /// <param name="pkrKeyRing">The public keyring containing /// all keys known to the local system.</param> public SignatureStatusTypes Verify(PublicKeyRing pkrKeyRing) { TransportablePublicKey tpkKey = pkrKeyRing.Find(spSignature.KeyID); if (tpkKey == null) { return(SignatureStatusTypes.Signing_Key_Not_Available); } PublicKeyPacket pkpKey = tpkKey.FindKey(spSignature.KeyID); spSignature.Verify(lmSignedMessage.Binary, pkpKey); return(spSignature.SignatureStatus); }
/// <summary> /// Validates all certificates belonging the the given public key packet /// and the current certifications. /// </summary> /// <remarks> /// So far only works with v4 signatures! /// </remarks> /// <param name="pkpKey">The public key packet to which the userid /// belongs.</param> /// <param name="pkrRing">A keyring containing all public keys known to /// the system. This is neccessary in order to verify the signatures. /// </param> public void Validate(PublicKeyPacket pkpKey, PublicKeyRing pkrRing) { IEnumerator ieCertificates = Certificates.GetEnumerator(); while (ieCertificates.MoveNext()) { if (ieCertificates.Current is SignaturePacket) { SignaturePacket spCert = (SignaturePacket)ieCertificates.Current; TransportablePublicKey tkpSigningKey = pkrRing.Find(spCert.KeyID); if (tkpSigningKey == null) { continue; } PublicKeyPacket pkpSigningKey = tkpSigningKey.PrimaryKey; if (spCert.Version == SignaturePacketVersionNumbers.v4) { byte[] bKey = new byte[pkpKey.Body.Length + 3]; bKey[0] = 0x99; bKey[1] = (byte)((pkpKey.Body.Length >> 8) & 0xFF); bKey[2] = (byte)(pkpKey.Body.Length & 0xFF); Array.Copy(pkpKey.Body, 0, bKey, 3, pkpKey.Body.Length); byte[] bUserID = new byte[UserID.Body.Length + 5]; bUserID[0] = 0xb4; bUserID[1] = (byte)((UserID.Body.Length >> 24) & 0xFF); bUserID[2] = (byte)((UserID.Body.Length >> 16) & 0xFF); bUserID[3] = (byte)((UserID.Body.Length >> 8) & 0xFF); bUserID[4] = (byte)(UserID.Body.Length & 0xFF); Array.Copy(UserID.Body, 0, bUserID, 5, UserID.Body.Length); byte[] bData = new byte[bUserID.Length + bKey.Length]; Array.Copy(bKey, 0, bData, 0, bKey.Length); Array.Copy(bUserID, 0, bData, bKey.Length, bUserID.Length); spCert.Verify(bData, pkpSigningKey); } else { //TODO: Add code for v3 Signature verification } } } }
void cmdDecode_Click(Object sender, System.EventArgs e) { byte[] bPlaintext = Radix64.Decode(txtRadix64.Text); string strOutput = ""; for (int i = 0; i < bPlaintext.Length; i++) { strOutput += bPlaintext[i].ToString() + ":"; } this.txtPlaintext.Text = strOutput; PublicKeyRing pkpRing = new PublicKeyRing(); pkpRing.Load("C:\\keyring.txt"); pkpRing.Save("C:\\keyringout.txt"); }
/// <summary> /// Validates all certificates belonging the the given public key packet /// and the current certifications. /// </summary> /// <remarks> /// So far only works with v4 signatures! /// </remarks> /// <param name="pkpKey">The public key packet to which the userid /// belongs.</param> /// <param name="pkrRing">A keyring containing all public keys known to /// the system. This is neccessary in order to verify the signatures. /// </param> public void Validate(PublicKeyPacket pkpKey, PublicKeyRing pkrRing) { IEnumerator ieCertificates = Certificates.GetEnumerator(); this.validitystatus = ValidityStatus.Valid; while (ieCertificates.MoveNext()) { if (ieCertificates.Current is SignaturePacket) { SignaturePacket spCert = (SignaturePacket)ieCertificates.Current; TransportablePublicKey tkpSigningKey = pkrRing.Find(spCert.KeyID, true); if (tkpSigningKey == null) { this.validitystatus = ValidityStatus.ValidationKeyUnavailable; continue; } PublicKeyPacket pkpSigningKey = tkpSigningKey.PrimaryKey; if (spCert.Version == SignaturePacketVersionNumbers.v4) { byte[] bKey = new byte[pkpKey.Body.Length + 3]; bKey[0] = 0x99; bKey[1] = (byte)((pkpKey.Body.Length >> 8) & 0xFF); bKey[2] = (byte)(pkpKey.Body.Length & 0xFF); Array.Copy(pkpKey.Body, 0, bKey, 3, pkpKey.Body.Length); byte[] bUserID = new byte[UserID.Body.Length + 5]; bUserID[0] = 0xb4; bUserID[1] = (byte)((UserID.Body.Length >> 24) & 0xFF); bUserID[2] = (byte)((UserID.Body.Length >> 16) & 0xFF); bUserID[3] = (byte)((UserID.Body.Length >> 8) & 0xFF); bUserID[4] = (byte)(UserID.Body.Length & 0xFF); Array.Copy(UserID.Body, 0, bUserID, 5, UserID.Body.Length); byte[] bData = new byte[bUserID.Length + bKey.Length]; Array.Copy(bKey, 0, bData, 0, bKey.Length); Array.Copy(bUserID, 0, bData, bKey.Length, bUserID.Length); spCert.Verify(bData, pkpSigningKey); if(spCert.SignatureStatus == SignatureStatusTypes.Invalid) { this.validitystatus = ValidityStatus.Invalid; continue; } else if(spCert.SignatureStatus == SignatureStatusTypes.Signing_Key_Not_Available) { this.validitystatus = ValidityStatus.ValidationKeyUnavailable; continue; } else if(spCert.SignatureStatus == SignatureStatusTypes.Not_Verified) { this.validitystatus = ValidityStatus.NotYetValidated; continue; } } else { //TODO: Add code for v3 Signature verification } } } }
private static void DecryptAndVerify(SecretKeyRing skrSecretKeyRing, PublicKeyRing pkrPublicKeyRing, byte[] bData) { 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.OpenPGP.Messages.Message mContent = null; if (atType == ArmorTypes.OpenPGPSignature) { 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 = Packet.ParsePackets(strSignature); if (!(pPackets[0] is SignaturePacket)) { MessageBox.Show("Not a valid cleartext signature!"); return; } 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(); try { Packet[] pPackets = Packet.ParsePackets(bData); emMessage.ParseMessage(pPackets); if (emMessage.SymmetricallyEncrypted) { // Query passphrase for symmetrically encrypted message QueryPassphrase qpPassphrase = new QueryPassphrase(); qpPassphrase.ShowMyDialog(); string strPassphrase = qpPassphrase.Passphrase; mContent = emMessage.Decrypt(strPassphrase); } else { ulong lKeyID = emMessage.GetFittingKeyID(skrSecretKeyRing); QueryPassphrase qpPassphrase = new QueryPassphrase(); qpPassphrase.ShowMyDialog(skrSecretKeyRing.Find(lKeyID)); string strPassphrase = qpPassphrase.Passphrase; mContent = emMessage.Decrypt(skrSecretKeyRing, strPassphrase); } while ((!(mContent is LiteralMessage)) && (!(mContent is SignedMessage))) { if (mContent is CompressedMessage) { mContent = ((CompressedMessage)mContent).Uncompress(); } else { MessageBox.Show("This is not a valid OpenPGP message!"); return; } } } catch (Exception ee) { MessageBox.Show("There was an error decrypting your message: " + ee.Message); return; } } 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: " + smContent.Signature.KeyID.ToString("x") + " ***\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 { MessageBox.Show("An error occured: Could not find an encrypted or signed message!", "Error..."); return; } if (lmContent.DataFormat == DataFormatTypes.Text) { strDisplay += lmContent.Text; strDisplay += "\r\n\r\n*** End OpenPGP Message ***\r\n"; PlaintextViewer pvViewer = new PlaintextViewer(); pvViewer.MessageText = strDisplay; pvViewer.Show(); } else { if (MessageBox.Show(strDisplay, "Signature Status...", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1) == DialogResult.OK) { System.Windows.Forms.SaveFileDialog sfdSave = new SaveFileDialog(); sfdSave.OverwritePrompt = true; sfdSave.Filter = "All Files (*.*)|*.*"; sfdSave.FileName = lmContent.Filename; sfdSave.ShowDialog(); if (sfdSave.FileName.Length > 0) { System.IO.FileStream fsOut = new FileStream(sfdSave.FileName, FileMode.CreateNew); System.IO.BinaryWriter bwOut = new BinaryWriter(fsOut); bwOut.Write(lmContent.Binary); bwOut.Close(); fsOut.Close(); } } } }
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; }
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(); }
public static void DecryptAndVerifyText(SecretKeyRing skrSecretKeyRing, PublicKeyRing pkrPublicKeyRing, string strMessage) { byte[] bData = new byte[strMessage.Length]; bData = System.Text.Encoding.UTF8.GetBytes(strMessage); DecryptAndVerify(skrSecretKeyRing, pkrPublicKeyRing, bData); }
public static void DecryptAndVerifyFile(SecretKeyRing skrSecretKeyRing, PublicKeyRing pkrPublicKeyRing, string strFile) { System.IO.FileStream fsIn = new FileStream(strFile, FileMode.Open); System.IO.BinaryReader brIn = new BinaryReader(fsIn); byte[] bData = new byte[fsIn.Length]; brIn.Read(bData, 0, bData.Length); DecryptAndVerify(skrSecretKeyRing, pkrPublicKeyRing, bData); }