locked
Encrypting and Decrypting RTF files? RRS feed

  • Question

  • Hi all,

    Just wondering if anybody can point me to a good tutorial on encrypting and decrypting RTF files?  I've found plenty of Encryption/Decryption tutorials on the net, but it's all about plaintext and encrypting passwords.  That's not what I need (at least, not yet, lol.)

    Here's the situation:

    My program is a MDI application that creates and opens files into a RichTextBox.  The program uses an Access database to store data.  I've set it up so that a user can create passwords for each individual file, which are then stored in the database. Also, using File.Encrypt() and System.IO.File.SetAttributes(), I've made it so that the user can set a file to only be opened on the system the program is on.  Now, I need to be able to encrypt the file so that if any program other than mine opens the file, even on the same system, all that'll be displayed is gibberish and to decrypt it in my program when the user enters the file's password.

    Thanks, as always! :)

    Jason

    Friday, September 12, 2014 4:16 AM

Answers

  • Jason,

    Food for thought here. You only want it to be able to be "read" from your program and you also want that if someone opens the file in a text reader (like NotePad), it will show gibberish.

    Here's what I set up - a form with a RichTextBox and two buttons:

    I opened an RTF file that I had on my desktop and copied it to the clipboard then pasted it into the RichTextBox:

    Now it's saved the binary file to my desktop (please note that file paths are all hard-coded in this - it was just for a test).

    Just to make sure that it would read it, I closed the program, re-opened it, and clicked the button to open the file:

    So it works but what's saved? The file extension is .bin but you can still open it in NotePad (like any other file):

    Well you wanted gibberish! ;-)

    The fact that it uses binary serialization, only your assembly can open it and the encryption also uses your assembly's name. Following is the code:

    Option Strict On Option Explicit On Imports System.IO Imports System.IO.Path Imports System.Runtime.Serialization.Formatters.Binary Imports System.Security.Cryptography Public Class Form1 Private s3D As New Simple3Des(My.Application.Info.AssemblyName) Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles MyBase.Load btn_SaveBinary.Enabled = False End Sub Private Sub RichTextBox1_TextChanged(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles RichTextBox1.TextChanged If RichTextBox1.Text.Trim <> "" Then btn_SaveBinary.Enabled = True Else btn_SaveBinary.Enabled = False End If End Sub Private Sub btn_SaveBinary_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles btn_SaveBinary.Click With btn_SaveBinary .Enabled = False .Refresh() End With Dim dt As String = My.Computer.FileSystem.SpecialDirectories.Desktop Dim filePath As String = Combine(dt, "RTF.bin") Using fs As New FileStream(filePath, FileMode.Create) Dim formatter As New BinaryFormatter formatter.Serialize(fs, s3D.EncryptData(RichTextBox1.Rtf)) End Using End Sub Private Sub btn_LoadBinary_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles btn_LoadBinary.Click Dim dt As String = My.Computer.FileSystem.SpecialDirectories.Desktop Dim filePath As String = Combine(dt, "RTF.bin") Using fs As New FileStream(filePath, FileMode.Open) Dim formatter As New BinaryFormatter() RichTextBox1.Rtf = s3D.DecryptData(DirectCast(formatter.Deserialize(fs), String)) End Using End Sub End Class ''' <summary> ''' A class for simple encryption as per MSDN document shown at: ''' http://msdn.microsoft.com/en-us/library/ms172831(v=vs.90).aspx ''' </summary> ''' <remarks></remarks> Public NotInheritable Class Simple3Des Private TripleDes As New TripleDESCryptoServiceProvider Sub New(ByVal key As String) ' Initialize the crypto provider. TripleDes.Key = TruncateHash(key, TripleDes.KeySize \ 8) TripleDes.IV = TruncateHash("", TripleDes.BlockSize \ 8) End Sub Public Function EncryptData(ByVal plaintext As String) _ As String ' Convert the plaintext string to a byte array. Dim plaintextBytes() As Byte = _ System.Text.Encoding.Unicode.GetBytes(plaintext) ' Create the stream. Dim ms As New System.IO.MemoryStream ' Create the encoder to write to the stream. Dim encStream As New CryptoStream(ms, _ TripleDes.CreateEncryptor(), _ System.Security.Cryptography.CryptoStreamMode.Write) ' Use the crypto stream to write the byte array to the stream. encStream.Write(plaintextBytes, 0, plaintextBytes.Length) encStream.FlushFinalBlock() ' Convert the encrypted stream to a printable string. Return Convert.ToBase64String(ms.ToArray) End Function Public Function DecryptData(ByVal encryptedtext As String) _ As String ' Convert the encrypted text string to a byte array. Dim encryptedBytes() As Byte = Convert.FromBase64String(encryptedtext) ' Create the stream. Dim ms As New System.IO.MemoryStream ' Create the decoder to write to the stream. Dim decStream As New CryptoStream(ms, _ TripleDes.CreateDecryptor(), _ System.Security.Cryptography.CryptoStreamMode.Write) ' Use the crypto stream to write the byte array to the stream. decStream.Write(encryptedBytes, 0, encryptedBytes.Length) decStream.FlushFinalBlock() ' Convert the plaintext stream to a string. Return System.Text.Encoding.Unicode.GetString(ms.ToArray) End Function Private Function TruncateHash(ByVal key As String, _ ByVal length As Integer) _ As Byte() Dim sha1 As New SHA1CryptoServiceProvider ' Hash the key. Dim keyBytes() As Byte = _ System.Text.Encoding.Unicode.GetBytes(key) Dim hash() As Byte = sha1.ComputeHash(keyBytes) ' Truncate or pad the hash. ReDim Preserve hash(length - 1) Return hash End Function End Class


    Something to consider. :)


    Still lost in code, just at a little higher level.

    :-)

    • Marked as answer by Jason Bodine Monday, September 15, 2014 2:26 AM
    Friday, September 12, 2014 5:58 PM

All replies

  • Just searching here will give you hundreds of examples, searching google will give you thousands. Look for terms like AES, Rijndael, .NET Encryption. I think Mr. Monkeyboy, one of our more prolific posters, has posted examples a few dozen times.

    See if this is what you want.
    • Edited by Devon_Nullman Friday, September 12, 2014 4:49 AM Added Hard Link
    Friday, September 12, 2014 4:45 AM
  • This is an RTF file created by wordpad. It is just plain text. Even if images were in it this would only be plain text. All .RTF files only contain plain text. However the text is what makes WordPad or a RichTextBox display whatever the formatting tells it to display.

    This .RTF file was created by WordPad. It has the word Hello in it, followed by a new line or two, following by a 20 x 20 pixel .Png image called Moon2.Png that was pasted into WordPad.

    So I suspect you would encrypt that text to store it and decrypt it to a string. Encrypt RichTextBox1.RTF then RichTextBox1.RTF = TheDecryptedString.

    {\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil\fcharset0 Calibri;}}
    {\*\generator Msftedit 5.41.21.2510;}\viewkind4\uc1\pard\sa200\sl276\slmult1\lang9\f0\fs22 Hello\par
    \pard\sa200\sl240\slmult1{\pict\wmetafile8\picw1191\pich1191\picwgoal675\pichgoal675 
    010009000003340c00000000150c000000000400000003010800050000000c02d3ff2d00050000
    000b020000000005000000070104000000150c0000410b2000cc002d002d0000000000d3ff2d00
    00000000280000002d0000002d0000000100180000000000e81700000000000000000000000000
    0000000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
    fffffffffffffffffffffffffffffffffffffffffffffff1f1f1eaeaeaf2f2f2e6e6e6f6f6f6f7
    f7f7fefefeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
    ffffffffffffffffffffffffffffffffffffffffffffff00ffffffffffffffffffffffffffffff
    fffffffffffffffffffffffffffffffffffffffffffefefefefefefffffffffffff6f6f6e8e8e8
    c9c9c9bebebed4d4d4a9a9a9b6b6b6abababc0c0c0bebebecfcfcfe1e1e1f0f0f0ffffffffffff
    fffffffefefeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
    ffffff00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
    fffffffffefefee7e7e7cacacacacacabebebeb3b3b3c1c1c1c6c6c6d2d2d2c5c5c5b6b6b6a8a8
    a8c9c9c9c1c1c1bbbbbbb8b8b8b8b8b8d7d7d7fbfbfbfffffffefefeffffffffffffffffffffff
    ffffffffffffffffffffffffffffffffffffffffffff00ffffffffffffffffffffffffffffffff
    ffffffffffffffffffffffffffffffffffffffffe7e7e7c7c7c7acacacbcbcbcc2c2c2cacacabd
    bdbdb8b8b8c6c6c6bbbbbbcececed2d2d2c3c3c3cdcdcdc5c5c5cecececececec2c2c2c0c0c0c2
    c2c2d6d6d6fffffffffffffefefeffffffffffffffffffffffffffffffffffffffffffffffffff
    ffff00fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff6f6f6afafaf
    bfbfbfc2c2c2c4c4c4cecececacacac2c2c2ababababababb9b9b9c2c2c2bdbdbdb4b4b4c4c4c4
    c1c1c1c7c7c7c6c6c6cacacac4c4c4bfbfbfaeaeaeb7b7b7bdbdbde0e0e0ffffffffffffffffff
    ffffffffffffffffffffffffffffffffffffffffff00ffffffffffffffffffffffffffffffffff
    ffffffffffffffffffffe8e8e8d0d0d0ccccccc9c9c9c5c5c5b7b7b7bbbbbbc4c4c4b2b2b2a5a5
    a5b6b6b6acacacb6b6b6a9a9a9bcbcbcc1c1c1c1c1c1c5c5c5bebebec1c1c1bcbcbcc7c7c7bfbf
    bfb2b2b2b8b8b8afafafc3c3c3ffffffffffffffffffffffffffffffffffffffffffffffffffff
    ff00ffffffffffffffffffffffffffffffffffffffffffffffffd9d9d9d5d5d5d9d9d9c9c9c9bc
    bcbcb4b4b4b2b2b2bababac8c8c8a9a9a9a5a5a5a1a1a1acacacbababab6b6b6c0c0c0aeaeaebf
    bfbfbebebeb2b2b2bdbdbdc0c0c0b4b4b49d9d9db3b3b3b6b6b6a2a2a2b6b6b6c3c3c3ffffffff
    ffffffffffffffffffffffffffffffffffffffff00ffffffffffffffffffffffffffffffffffff
    ffffffdadadab6b6b6c9c9c9babababcbcbca6a6a69e9e9e9d9d9dbbbbbbc1c1c19d9d9d9c9c9c
    afafafc8c8c8c9c9c9b0b0b0c2c2c2b2b2b2bcbcbcbdbdbdbdbdbdafafafafafafb7b7b7b6b6b6
    979797b0b0b0b7b7b7a8a8a8b3b3b3c1c1c1f6f6f6ffffffffffffffffffffffffffffffffffff
    00ffffffffffffffffffffffffffffffffffffdfdfdfd8d8d8c5c5c5bbbbbbc4c4c4a3a3a39292
    928f8f8f9494949f9f9fa5a5a5999999b3b3b3b8b8b8a7a7a7c5c5c5afafafcacacabfbfbfb8b8
    b8b9b9b9bbbbbbc2c2c2bdbdbdb0b0b0aeaeaebebebea9a9a9b7b7b7adadada9a9a9a9a9a9c4c4
    c4ffffffffffffffffffffffffffffffffffff00fffffffffffffffffffefefeffffffe0e0e0db
    dbdbd2d2d2c9c9c9c3c3c3b8b8b89f9f9f949494949494a4a4a4c7c7c79b9b9bb1b1b1b6b6b6a5
    a5a5b4b4b4b0b0b0afafafadadadbbbbbbbbbbbbb5b5b5b2b2b2b1b1b1c5c5c5acacacb0b0b0a8
    a8a8b4b4b4a1a1a1adadadb4b4b4b2b2b2989898c7c7c7fffffffefefeffffffffffffffffff00
    fffffffffffffffffffffffff5f5f5cdcdcdc5c5c5c4c4c4cececec3c3c3c2c2c29c9c9c9b9b9b
    a1a1a1bbbbbbb1b1b1b8b8b8a7a7a7a0a0a0adadad9e9e9ea3a3a3bbbbbb989898adadadb2b2b2
    9f9f9fbdbdbd9f9f9fa2a2a2c7c7c7a5a5a5a8a8a8acacacb8b8b8acacacaeaeaeabababb3b3b3
    9d9d9de7e7e7ffffffffffffffffffffffff00ffffffffffffffffffffffffc7c7c7ccccccc4c4
    c4c0c0c0c6c6c6bebebea8a8a8b4b4b49e9e9e9797979b9b9ba3a3a3b4b4b49f9f9fa6a6a6a2a2
    a29c9c9c8d8d8da4a4a4a2a2a2969696a6a6a6b4b4b4abababbcbcbc9e9e9ea8a8a8bfbfbf9d9d
    9db3b3b3b0b0b0b1b1b1afafafb6b6b6a4a4a4a1a1a1adadadfefefeffffffffffffffffff00ff
    ffffffffffffffffdededec8c8c8cbcbcbc3c3c3bdbdbda8a8a8aeaeaeb3b3b3a1a1a18b8b8b8e
    8e8e929292a1a1a1bababaaaaaaac6c6c6a1a1a18c8c8ccdcdcdaaaaaabebebe9d9d9db1b1b1ac
    acacabababadadadb3b3b3a1a1a1b0b0b0bababaa8a8a89c9c9c9e9e9ea4a4a4a0a0a0b2b2b2b2
    b2b2bcbcbccacacaffffffffffffffffff00fffffffffffffbfbfbc7c7c7b1b1b1b7b7b7a6a6a6
    a1a1a1999999919191919191878787868686969696a4a4a49797979c9c9c9c9c9cb0b0b0b0b0b0
    aaaaaaaeaeae9a9a9a9d9d9db4b4b4bbbbbbafafafbcbcbc9d9d9db7b7b79f9f9fa5a5a5b6b6b6
    a8a8a89f9f9fa1a1a19090909f9f9fb2b2b2c4c4c4bbbbbbb7b7b7fbfbfbfefefeffffff00ffff
    ffffffffdddddd9a9a9abfbfbf9d9d9d979797adadad949494909090999999878787969696c1c1
    c1a5a5a59999999898989f9f9faeaeaeb1b1b1bfbfbf979797b2b2b2b4b4b4a4a4a4acacaca9a9
    a9bbbbbba4a4a4b2b2b29f9f9facacaca4a4a4b4b4b4949494a1a1a1989898a8a8a8c0c0c0cbcb
    cbbdbdbdb0b0b0c8c8c8ffffffffffff00ffffffffffffaeaeaec9c9c9a9a9a991919192929292
    9292939393949494969696969696989898adadada9a9a9979797a8a8a8b5b5b5b3b3b3aeaeaebd
    bdbdaaaaaabebebe949494bdbdbda9a9a9b0b0b0adadadacacacaeaeaeaaaaaaadadad9e9e9eb3
    b3b3a9a9a9a0a0a0abababb7b7b7b3b3b3c2c2c2b1b1b1b2b2b2b2b2b2ffffffffffff00ffffff
    f2f2f2b7b7b7aaaaaa9595958e8e8e919191919191949494909090919191979797999999a9a9a9
    9d9d9dacacacbbbbbbc9c9c9adadadc9c9c9c5c5c5a3a3a3a5a5a5bababaa4a4a49b9b9bb0b0b0
    b1b1b1b4b4b4bdbdbdbebebeb2b2b2b7b7b7a5a5a58d8d8da6a6a6a3a3a3aaaaaaacacac9c9c9c
    b4b4b4a7a7a7afafafe3e3e3ffffff00ffffffdfdfdfbdbdbda0a0a08787878888888e8e8e9494
    94909090a5a5a59d9d9d959595a6a6a6a9a9a99d9d9da5a5a5afafafc7c7c7b9b9b9c2c2c2c8c8
    c8a9a9a9b0b0b0aeaeaebbbbbb9e9e9ea5a5a5b2b2b2b8b8b8b1b1b1c0c0c0b1b1b1a0a0a08f8f
    8f8282827f7f7f8f8f8fb4b4b49797979f9f9fa1a1a1a8a8a8a7a7a7cfcfcfffffff00ffffffd3
    d3d3b7b7b7959595878787868686898989949494a5a5a5adadadadadada4a4a4a4a4a4b7b7b7b2
    b2b2c4c4c4c8c8c8babababdbdbdbbbbbbbbbbbbacacaca4a4a4adadadb4b4b4bababab1b1b1ad
    adadb7b7b7b3b3b3d0d0d0a4a4a4ababab9d9d9d9090907c7c7c999999b9b9b99797978d8d8d90
    9090b7b7b7a6a6a6c5c5c5ffffff00ffffffcccccca9a9a98b8b8b8888888d8d8d8e8e8ea0a0a0
    b8b8b8cacacab9b9b9a8a8a8c2c2c2c3c3c3c0c0c0cececec9c9c9c1c1c1a9a9a9afafafb2b2b2
    979797afafafa4a4a4a9a9a9b8b8b8b1b1b1b4b4b4bfbfbfc3c3c39d9d9d9999999797978f8f8f
    9494948a8a8ab5b5b5afafafa7a7a7999999a3a3a3959595a7a7a7b2b2b2ffffff00fefefebebe
    beaaaaaa8888888989899191919292929a9a9ac0c0c0cacacabdbdbdaaaaaac2c2c2d0d0d0c9c9
    c9b8b8b8bdbdbdadadadababab9a9a9ab0b0b0a9a9a9a7a7a7c2c2c29f9f9facacacc0c0c0b0b0
    b0afafafbbbbbbb7b7b78585859393938f8f8facacacb8b8b8c5c5c5aaaaaab1b1b1b6b6b69999
    99a2a2a29b9b9bb0b0b0ffffff00ffffffb8b8b89292928585858a8a8a8888889191919d9d9db0
    b0b0cfcfcfacacac969696c6c6c6d8d8d8c2c2c2afafafc0c0c0bababaa0a0a0aaaaaac8c8c8bc
    bcbcc3c3c3acacacc2c2c2bcbcbcbbbbbbafafafa1a1a1b9b9b9cccccca6a6a6858585a6a6a6bb
    bbbbaeaeaeb8b8b8a9a9a99292928c8c8c919191adadadacacaca4a4a4fcfcfc00ffffffb0b0b0
    8585858989898383838d8d8d8f8f8f9e9e9ebbbbbbb1b1b1989898aeaeaecfcfcfd7d7d7c2c2c2
    b3b3b3c3c3c3b2b2b2a8a8a8b2b2b2b7b7b7b8b8b8bdbdbdaeaeaeb9b9b9b8b8b8acacaca6a6a6
    bebebeaeaeae9999998e8e8e838383b3b3b3b1b1b1b4b4b4b0b0b09595958d8d8d8e8e8e969696
    c0c0c0b6b6b6999999f5f5f500ffffffa2a2a28282827e7e7e8888889393939c9c9c9e9e9ec0c0
    c0a7a7a7a0a0a0bfbfbfc9c9c9d5d5d5c0c0c0c9c9c9c5c5c5b4b4b49898989e9e9eb2b2b2b8b8
    b8b1b1b1b0b0b0b7b7b7bbbbbbc5c5c5bdbdbda4a4a49d9d9d9999998686867c7c7cb3b3b3b7b7
    b7a1a1a19c9c9c8484848c8c8c8a8a8a9f9f9fbebebeababab979797f7f7f700ffffffb2b2b286
    86867a7a7a9494949e9e9eb4b4b4b4b4b4a4a4a4a6a6a6a6a6a6b6b6b6cbcbcbc7c7c7c2c2c2bb
    bbbbbbbbbba9a9a98f8f8fa2a2a2a3a3a38d8d8d999999929292adadadc8c8c8b1b1b1bfbfbf9c
    9c9c9c9c9c9292927d7d7d7e7e7ea0a0a09191918d8d8d9d9d9d919191959595909090a0a0a0a9
    a9a9aaaaaaa7a7a7fafafa00ffffffb8b8b88282827474747b7b7bb0b0b0bdbdbda6a6a6a0a0a0
    8d8d8d9c9c9caaaaaaa5a5a5bababaadadadb2b2b2aeaeaeb5b5b5a9a9a9919191a8a8a8919191
    8989899e9e9eb2b2b2bbbbbba9a9a9bbbbbb9c9c9c9595959c9c9c808080818181797979727272
    8080809f9f9f9c9c9c9393938d8d8d979797a8a8a8a4a4a4bbbbbbffffff00ffffffb1b1b18484
    846e6e6e717171939393b8b8b8999999909090909090909090b9b9b99f9f9fbbbbbbadadadadad
    ada2a2a2a6a6a69a9a9aa0a0a0989898979797989898afafafb1b1b1a6a6a6b3b3b39595959494
    948989899696969292928686868080808484848e8e8ea0a0a09494948787878e8e8ea1a1a1a1a1
    a1afafafc9c9c9ffffff00ffffffcecece9494947373736f6f6f858585aaaaaa9393938989898b
    8b8b8888888b8b8b949494b6b6b6b1b1b1a6a6a69191919696968e8e8eacacacafafafaaaaaa94
    9494a4a4a4a6a6a6b8b8b8aaaaaa9d9d9d8686868282829393939797978e8e8e8c8c8c939393b2
    b2b29a9a9a9e9e9e9d9d9db3b3b3bebebe9b9b9baeaeaed5d5d5ffffff00ffffffe9e9e97d7d7d
    7f7f7f7a7a7a7b7b7b8e8e8e8383838888888585858c8c8c8d8d8d9898989797979d9d9da0a0a0
    9797978f8f8f9a9a9a979797abababb0b0b0a4a4a49d9d9d9e9e9e9d9d9d9d9d9da4a4a4a1a1a1
    8181818c8c8c9e9e9e8d8d8d8b8b8b9797979e9e9ea7a7a7acacacd4d4d4bfbfbfc7c7c7c1c1c1
    b0b0b0e4e4e4ffffff00fffffffcfcfc8b8b8b7575758484847f7f7f7d7d7d7a7a7a7f7f7f9e9e
    9e9d9d9d8c8c8c939393969696959595909090999999a0a0a09e9e9e989898c1c1c1a2a2a27c7c
    7c7e7e7e8c8c8c9898989797979191918484848181817e7e7e9999999090908a8a8aa8a8a8aeae
    aec8c8c8dadadab4b4b4c3c3c3adadadabababcececefcfcfcffffff00ffffffffffffc0c0c074
    74747272728484847e7e7e7979798484849595958787878989898d8d8d8c8c8c87878789898983
    8383888888999999a4a4a4b8b8b89090908080808b8b8b90909097979796969699999989898988
    8888acacaca4a4a48f8f8fa7a7a7bbbbbbbababac5c5c5a8a8a8939393abababd8d8d89c9c9cd6
    d6d6ffffffffffff00fffffffffffff0f0f0808080717171797979808080959595969696929292
    8a8a8a8585858686868686868585858383838686868a8a8a909090a1a1a19393938686868a8a8a
    9292929292929595959696969393938e8e8e989898bcbcbc9191919d9d9db1b1b1c8c8c8c9c9c9
    a4a4a48989898181818b8b8bc4c4c4bbbbbbeeeeeeffffffffffff00ffffffffffffffffffa6a6
    a67373737878787d7d7da2a2a2bebebea1a1a18c8c8c8787878a8a8a8888888888888a8a8a8585
    859191919696969b9b9b9696969797978c8c8c8f8f8f929292939393979797969696929292baba
    bab3b3b3a7a7a7c3c3c3d1d1d1c3c3c3c3c3c39999998181818383838b8b8bc5c5c5c5c5c5ffff
    fffefefeffffff00ffffffffffffffffffe7e7e76d6d6d7d7d7d808080a6a6a6a4a4a4cdcdcd8b
    8b8b8a8a8a8888888989898a8a8a8585858f8f8f9393939c9c9c919191a9a9a99a9a9a8a8a8a90
    90908e8e8e979797969696929292a3a3a3b9b9b9d1d1d1c3c3c3ccccccb9b9b9b7b7b7adadad89
    8989818181818181a6a6a6b5b5b5efefefffffffffffffffffff00ffffffffffffffffffffffff
    c2c2c2777777858585989898cecececfcfcf8888889494948e8e8e9191918d8d8d898989909090
    9b9b9b959595939393afafafa8a8a89191919494949191919f9f9f949494a1a1a1abababc5c5c5
    bebebeb7b7b7b8b8b8b2b2b2b3b3b3b2b2b29b9b9b8a8a8a9a9a9ac5c5c5d4d4d4ffffffffffff
    ffffffffffff00fffffffffffffffffffefefeffffffa6a6a68282828080808f8f8fd9d9d9c9c9
    c9a1a1a1afafaf9393939393938b8b8b9191919292929797979c9c9cacacacb3b3b3b7b7b7bfbf
    bfc2c2c2afafaf9d9d9db3b3b3abababb6b6b6c8c8c8bdbdbda6a6a6babababdbdbda9a9a9b2b2
    b2b6b6b6b4b4b4c9c9c9fffffffefefeffffffffffffffffff00ffffffffffffffffffffffffff
    fffff9f9f9999999979797838383a7a7a7d1d1d1cdcdcdc5c5c5b2b2b2a2a2a29797979a9a9a98
    9898999999898989a1a1a1b3b3b3c0c0c0c4c4c4b7b7b79f9f9f9e9e9e9d9d9da4a4a4a5a5a5b5
    b5b5b7b7b7b6b6b6c6c6c6a7a7a7b1b1b1bcbcbcb8b8b8c4c4c4f7f7f7ffffffffffffffffffff
    ffffffffff00ffffffffffffffffffffffffffffffffffffecececc3c3c3bcbcbca6a6a6999999
    a4a4a4c4c4c4c0c0c0c8c8c8bcbcbc9b9b9bb1b1b1afafaf8c8c8c939393989898b1b1b1aaaaaa
    9f9f9fa6a6a6a3a3a3aeaeaeacacacc8c8c8bcbcbcadadadc3c3c3bbbbbbadadadb4b4b4bbbbbb
    b7b7b7f1f1f1ffffffffffffffffffffffffffffffffffff00ffffffffffffffffffffffffffff
    fffffffffffffff1f1f1c3c3c3d3d3d3b9b9b9a8a8a8a1a1a19f9f9faaaaaaaaaaaabfbfbfb9b9
    b9a9a9a98b8b8b949494a3a3a3b3b3b3a0a0a0a2a2a2a2a2a2acacacb8b8b8c7c7c7a9a9a9b0b0
    b0aeaeaeb1b1b1bcbcbcbababab1b1b19e9e9ef2f2f2ffffffffffffffffffffffffffffffffff
    ffffffff00fffffffffffffffffffffffffffffffffffffffffffffffff4f4f4b2b2b2cdcdcdc2
    c2c2aeaeae9d9d9d9292929292929696969b9b9b9292928b8b8b8f8f8f9494949c9c9cb7b7b79d
    9d9da7a7a7b0b0b09b9b9b9f9f9fa5a5a5b8b8b8b1b1b1b2b2b2afafafc3c3c3bfbfbff5f5f5ff
    ffffffffffffffffffffffffffffffffffffffffffffff00ffffffffffffffffffffffffffffff
    fffffffffffffffffffffffffefefedbdbdbc6c6c6c8c8c8c6c6c6c7c7c79595959191918b8b8b
    8a8a8a9d9d9d9393938e8e8e898989919191979797afafafa9a9a9a2a2a2abababb3b3b3ababab
    b9b9b9c7c7c7c2c2c2ddddddffffffffffffffffffffffffffffffffffffffffffffffffffffff
    ffffff00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecec
    ecc4c4c4bdbdbdcacacad0d0d0b0b0b0aeaeaebbbbbbb0b0b0a9a9a99d9d9d9e9e9e8f8f8fb0b0
    b0aaaaaab9b9b9a9a9a9afafaf999999b0b0b0adadadd0d0d0f9f9f9fffffffefefeffffffffff
    ffffffffffffffffffffffffffffffffffffffffffff00ffffffffffffffffffffffffffffffff
    ffffffffffffffffffffffffffffffffffffffffffffffefefefcdcdcdc7c7c7cdcdcdd1d1d1b3
    b3b3aeaeaeafafafa2a2a2bcbcbcccccccbdbdbdc4c4c4c7c7c7a5a5a5a1a1a1c6c6c6d0d0d0f3
    f3f3fdfdfdfefefeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
    ffff00fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffefefe
    fefefefffffffffffff8f8f8e2e2e2d2d2d2bababaadadada8a8a8a2a2a2a4a4a4acacacb8b8b8
    a6a6a6b7b7b7b8b8b8d5d5d5fafafafffffffffffffffffffdfdfdffffffffffffffffffffffff
    ffffffffffffffffffffffffffffffffffffffffff00ffffffffffffffffffffffffffffffffff
    fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffdfd
    fdf6f6f6f3f3f3f3f3f3f6f6f6f3f3f3ebebebf4f4f4ffffffffffffffffffffffffffffffffff
    ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
    ff00030000000000
    }\par
    \pard\sa200\sl276\slmult1\par
    }
     

     


    La vida loca

    Friday, September 12, 2014 4:46 AM
  • Mr. MonkeyBoy:

    Can this be used from the OpenFileDialog to decrypt the file when it is opened into the child form, or would I need to put the code in the child form itself(which has the richtextbox on it?)

    Jason

    Friday, September 12, 2014 5:20 AM
  • Mr. MonkeyBoy:

    Can this be used from the OpenFileDialog to decrypt the file when it is opened into the child form, or would I need to put the code in the child form itself(which has the richtextbox on it?)

    Jason

    I've never used mdi forms and am unfamiliar with them.

    Can't a parent form of a child form pass data to a control in a child form? Like one form can pass data to a control on another form? Like with two Forms Form1 would tell Form2 to display text in Form2's richtext box by using Form2.RichTextBox1.Text = "something"?

    Of course the code can be used with a save file dialog and an open file dialog in order to save the RTF encrypted text to some filename and open a file to decrypt from some filename. I would just make up some extension that isn't used by any other app on your system. Like maybe .Crypto or something.

    I used .enc as the file extension thinking no other app uses that extension but later when I clicked on one of those encrypted files an application (Network analyzer) called WireShark launched and tried to display the file as that's an extension WireShark uses to save captures to. WireShark displayed an error trying to display that files data.


    La vida loca



    Friday, September 12, 2014 5:58 AM
  • That'd take care of encrypting and decrypting within the program, but what about outside of it? After all, encrypting an rtf file or any other file seems kind of pointless if someone who REALLY wants to look at whatever the file contains can just open the file up in Wordpad!

    Jason

    Friday, September 12, 2014 6:12 AM
  • That'd take care of encrypting and decrypting within the program, but what about outside of it? After all, encrypting an rtf file or any other file seems kind of pointless if someone who REALLY wants to look at whatever the file contains can just open the file up in Wordpad!

    Jason

    I don't know what you mean.

    This is the encrypted text of the word Hello using the password superman to encrypt its text. I opened the file EncryptAndDecrypt.enc on my desktop and that's what is displayed in it. Not clear text.

    Regardless this code was originally used to only encrypt and decrypt short strings. It seems to be having an issue trying  to encrypt an RTF files text for some reason.

    But it's late here and I'm going to sleep. I have other code that can encrypt and decrypt any file with no problem. The only issue is trying to associate a password to it like this code does. I'll try to figure it out tomorrow.

    YWepv2z4vHP9+tvG2Q7qAQ==


    La vida loca


    Friday, September 12, 2014 6:34 AM
  • Sorry about the delay. I deleted the post with the previous code in it and went with the Rijndael method which is probably the best method right now. Anyhow the link for that class is in the code below.

    This uses a 32 byte key (256 bit key) and 16 byte initialization vector (IV) (128 bit IV).

    In the Form Load event the same key and vector List(Of Byte) are always created the same. However two other List(Of Byte) use the password from 6 to 12 characters as their first 6 to 12 bytes. Then for the rest of their bytes they use the bytes out of the key and vector List(Of Byte). So if you use this alter all the bytes in the Form Load for the Key and IV lists to whatever characters you want to use.

    Since the TextBox password characters are converted to bytes the passwords are case sensitive and any keyboard character can be used.

    The user should type a 6 to 12 character password in textbox1 after RichTextBox1 contains something (Text, Image, etc) and select button1. I used .Cryptified for a file extension although that gives away that the file is an encrypted file obviously. But you could use something of at least 5 letters probably as most file extensions are not that long so you probably will not match one used by other applications.

    So in TextBox1 I typed superduper for the password. And in RTB1 I typed the word Hello and two line feeds and pasted the image in it. Saved RTB1's RTF encrypted to a file. Then typed a password "superduper" in TextBox2 and selected the encrypted file to decrypt and made RichTextBox2.RTF = the decrypted text. And you can see RTB2 displays Hello and the image just like RTB1.

    The encrypted file is called TestOfRTFEncryption.Cryptified. It is 624,752 bytes in size. Opened in Notepad the information in it displays like below.

    Ö|­WðQ¡Ð¦ 7b€ŒþÜ%¡Np»¼b* ‘!ÙàÁ9ÿ÷®Z ó<ç
    Þ›”é¿PÉs±KÌDÑô?Ù [æE¸ÀälÜ|z*¤q
    \îQõ»¯½»*íFʬ'¹ÌÂœFϱOÄŠlã?#ÛöYÔÁ-Ï©štg&M*Þ°48Ž~^âRzóé¥æâßÁò
    Èç«Ñ˜+"¥¿ àš(ځHï¿ó­

    Form1 Code.

    Option Strict On
    
    Imports System.IO
    Imports System.Security.Cryptography
    
    Public Class Form1
    
        ' An auto created key is 32 bytes
        ' An auto created IV is 16 bytes
        ' Code is from Rijndael Class link http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndael.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1
    
        Dim KeyandIV As Rijndael
        Dim KeyToUse As New List(Of Byte)
        Dim IVToUse As New List(Of Byte)
        Dim KeyAfterPassword As New List(Of Byte)
        Dim IVAfterPassword As New List(Of Byte)
    
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Me.Location = New Point(CInt((Screen.PrimaryScreen.WorkingArea.Width / 2) - (Me.Width / 2)), CInt((Screen.PrimaryScreen.WorkingArea.Height / 2) - (Me.Height / 2)))
            KeyandIV = Rijndael.Create
            KeyToUse.Add(AscW("L"))
            KeyToUse.Add(AscW("p"))
            KeyToUse.Add(AscW("-"))
            KeyToUse.Add(AscW("1"))
            KeyToUse.Add(AscW("g"))
            KeyToUse.Add(AscW("Z"))
            KeyToUse.Add(AscW("$"))
            KeyToUse.Add(AscW("|"))
            KeyToUse.Add(AscW("0"))
            KeyToUse.Add(AscW("J"))
            KeyToUse.Add(AscW("<"))
            KeyToUse.Add(AscW("@"))
            KeyToUse.Add(AscW("U"))
            KeyToUse.Add(AscW("w"))
            KeyToUse.Add(AscW("8"))
            KeyToUse.Add(AscW("."))
            KeyToUse.Add(AscW("["))
            KeyToUse.Add(AscW("k"))
            KeyToUse.Add(AscW("="))
            KeyToUse.Add(AscW("1"))
            KeyToUse.Add(AscW(":"))
            KeyToUse.Add(AscW("7"))
            KeyToUse.Add(AscW("\"))
            KeyToUse.Add(AscW("?"))
            KeyToUse.Add(AscW("6"))
            KeyToUse.Add(AscW("r"))
            KeyToUse.Add(AscW("*"))
            KeyToUse.Add(AscW(","))
            KeyToUse.Add(AscW("3"))
            KeyToUse.Add(AscW("#"))
            KeyToUse.Add(AscW("D"))
            KeyToUse.Add(AscW("I"))
    
            IVToUse.Add(AscW("-"))
            IVToUse.Add(AscW("1"))
            IVToUse.Add(AscW("g"))
            IVToUse.Add(AscW("Z"))
            IVToUse.Add(AscW("$"))
            IVToUse.Add(AscW("|"))
            IVToUse.Add(AscW("0"))
            IVToUse.Add(AscW("J"))
            IVToUse.Add(AscW("<"))
            IVToUse.Add(AscW("@"))
            IVToUse.Add(AscW("U"))
            IVToUse.Add(AscW("w"))
            IVToUse.Add(AscW("8"))
            IVToUse.Add(AscW("."))
            IVToUse.Add(AscW("["))
            IVToUse.Add(AscW("k"))
    
        End Sub
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            KeyAfterPassword.Clear()
            IVAfterPassword.Clear()
            If TextBox1.Text <> "" Then
                If TextBox1.Text.Count > 5 And TextBox1.Text.Count < 13 Then
                    For i = 0 To TextBox1.Text.Count - 1
                        KeyAfterPassword.Add(CByte(AscW(TextBox1.Text(i))))
                    Next
                    For i = TextBox1.Text.Count To KeyToUse.Count - 1
                        KeyAfterPassword.Add(KeyToUse(i))
                    Next
                    KeyandIV.Key = KeyAfterPassword.ToArray
                    For i = 0 To TextBox1.Text.Count - 1
                        IVAfterPassword.Add(CByte(AscW(TextBox1.Text(i))))
                    Next
                    For i = TextBox1.Text.Count To IVToUse.Count - 1
                        IVAfterPassword.Add(IVToUse(i))
                    Next
                    KeyandIV.IV = IVAfterPassword.ToArray
                    If RichTextBox1.Rtf <> "" Then
                        Dim SFD As New SaveFileDialog
                        SFD.Filter = "Encrypted files (*.Cryptified)|*.Cryptified"
                        SFD.Title = "Encrypt RichTextBox RTF"
                        SFD.InitialDirectory = "C:\Users\John\Desktop"
                        If SFD.ShowDialog = Windows.Forms.DialogResult.OK Then
                            Dim encrypted As Byte() = EncryptStringToBytes(RichTextBox1.Rtf, KeyandIV.Key, KeyandIV.IV)
                            My.Computer.FileSystem.WriteAllBytes(SFD.FileName, encrypted, False)
                        End If
                        SFD.Dispose()
                    Else
                        MessageBox.Show("RichTextBox1 is empty, please try again.")
                    End If
                Else
                    MessageBox.Show("TextBox1 must contain from 6 to 12 characters only.")
                End If
            Else
                MessageBox.Show("TextBox1 must contain a password of 6 to 12 characters only.")
            End If
    
        End Sub
    
        Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
            KeyAfterPassword.Clear()
            IVAfterPassword.Clear()
            If TextBox2.Text <> "" Then
                If TextBox2.Text.Count > 5 And TextBox2.Text.Count < 13 Then
                    For i = 0 To TextBox2.Text.Count - 1
                        KeyAfterPassword.Add(CByte(AscW(TextBox2.Text(i))))
                    Next
                    For i = TextBox2.Text.Count To KeyToUse.Count - 1
                        KeyAfterPassword.Add(KeyToUse(i))
                    Next
                    KeyandIV.Key = KeyAfterPassword.ToArray
                    For i = 0 To TextBox2.Text.Count - 1
                        IVAfterPassword.Add(CByte(AscW(TextBox2.Text(i))))
                    Next
                    For i = TextBox2.Text.Count To IVToUse.Count - 1
                        IVAfterPassword.Add(IVToUse(i))
                    Next
                    KeyandIV.IV = IVAfterPassword.ToArray
                    Dim OFD As New OpenFileDialog
                    OFD.Filter = "Encrypted files (*.Cryptified)|*.Cryptified"
                    OFD.Title = "Decrypt RichTextBox RTF file"
                    OFD.InitialDirectory = "C:\Users\John\Desktop"
                    OFD.Multiselect = False
                    If OFD.ShowDialog = Windows.Forms.DialogResult.OK Then
                        Dim Decrypted As Byte() = My.Computer.FileSystem.ReadAllBytes(OFD.FileName)
                        RichTextBox2.Rtf = DecryptStringFromBytes(Decrypted, KeyandIV.Key, KeyandIV.IV)
                    End If
                    OFD.Dispose()
                Else
                    MessageBox.Show("TextBox2 must contain from 6 to 12 characters only.")
            End If
            Else
                MessageBox.Show("TextBox2 must contain a password of 6 to 12 characters only.")
            End If
        End Sub
    
        Shared Function EncryptStringToBytes(ByVal plainText As String, ByVal Key() As Byte, ByVal IV() As Byte) As Byte()
            ' Check arguments. 
            If plainText Is Nothing OrElse plainText.Length <= 0 Then
                Throw New ArgumentNullException("plainText")
            End If
            If Key Is Nothing OrElse Key.Length <= 0 Then
                Throw New ArgumentNullException("Key")
            End If
            If IV Is Nothing OrElse IV.Length <= 0 Then
                Throw New ArgumentNullException("Key")
            End If
            Dim encrypted() As Byte
            ' Create an Rijndael object 
            ' with the specified key and IV. 
            Using rijAlg = Rijndael.Create()
    
                rijAlg.Key = Key
                rijAlg.IV = IV
    
                ' Create a decrytor to perform the stream transform. 
                Dim encryptor As ICryptoTransform = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV)
                ' Create the streams used for encryption. 
                Using msEncrypt As New MemoryStream()
                    Using csEncrypt As New CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)
                        Using swEncrypt As New StreamWriter(csEncrypt)
    
                            'Write all data to the stream.
                            swEncrypt.Write(plainText)
                        End Using
                        encrypted = msEncrypt.ToArray()
                    End Using
                End Using
            End Using
    
            ' Return the encrypted bytes from the memory stream. 
            Return encrypted
    
        End Function 'EncryptStringToBytes
    
        Shared Function DecryptStringFromBytes(ByVal cipherText() As Byte, ByVal Key() As Byte, ByVal IV() As Byte) As String
            Try
                ' Check arguments. 
                If cipherText Is Nothing OrElse cipherText.Length <= 0 Then
                    Throw New ArgumentNullException("cipherText")
                End If
                If Key Is Nothing OrElse Key.Length <= 0 Then
                    Throw New ArgumentNullException("Key")
                End If
                If IV Is Nothing OrElse IV.Length <= 0 Then
                    Throw New ArgumentNullException("Key")
                End If
                ' Declare the string used to hold 
                ' the decrypted text. 
                Dim plaintext As String = Nothing
    
                ' Create an Rijndael object 
                ' with the specified key and IV. 
                Using rijAlg = Rijndael.Create()
                    rijAlg.Key = Key
                    rijAlg.IV = IV
    
                    ' Create a decrytor to perform the stream transform. 
                    Dim decryptor As ICryptoTransform = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV)
    
                    ' Create the streams used for decryption. 
                    Using msDecrypt As New MemoryStream(cipherText)
    
                        Using csDecrypt As New CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)
    
                            Using srDecrypt As New StreamReader(csDecrypt)
    
    
                                ' Read the decrypted bytes from the decrypting stream 
                                ' and place them in a string.
                                plaintext = srDecrypt.ReadToEnd()
                            End Using
                        End Using
                    End Using
                End Using
    
                Return plaintext
            Catch ex As Exception
                MessageBox.Show(ex.Message & vbCrLf & "Invalid password used")
            End Try
    
        End Function 'DecryptStringFromBytes 
    
    End Class



    La vida loca







    • Edited by Mr. Monkeyboy Friday, September 12, 2014 3:47 PM
    • Proposed as answer by Devon_Nullman Friday, September 12, 2014 5:56 PM
    Friday, September 12, 2014 3:27 PM
  • Jason,

    Food for thought here. You only want it to be able to be "read" from your program and you also want that if someone opens the file in a text reader (like NotePad), it will show gibberish.

    Here's what I set up - a form with a RichTextBox and two buttons:

    I opened an RTF file that I had on my desktop and copied it to the clipboard then pasted it into the RichTextBox:

    Now it's saved the binary file to my desktop (please note that file paths are all hard-coded in this - it was just for a test).

    Just to make sure that it would read it, I closed the program, re-opened it, and clicked the button to open the file:

    So it works but what's saved? The file extension is .bin but you can still open it in NotePad (like any other file):

    Well you wanted gibberish! ;-)

    The fact that it uses binary serialization, only your assembly can open it and the encryption also uses your assembly's name. Following is the code:

    Option Strict On Option Explicit On Imports System.IO Imports System.IO.Path Imports System.Runtime.Serialization.Formatters.Binary Imports System.Security.Cryptography Public Class Form1 Private s3D As New Simple3Des(My.Application.Info.AssemblyName) Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles MyBase.Load btn_SaveBinary.Enabled = False End Sub Private Sub RichTextBox1_TextChanged(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles RichTextBox1.TextChanged If RichTextBox1.Text.Trim <> "" Then btn_SaveBinary.Enabled = True Else btn_SaveBinary.Enabled = False End If End Sub Private Sub btn_SaveBinary_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles btn_SaveBinary.Click With btn_SaveBinary .Enabled = False .Refresh() End With Dim dt As String = My.Computer.FileSystem.SpecialDirectories.Desktop Dim filePath As String = Combine(dt, "RTF.bin") Using fs As New FileStream(filePath, FileMode.Create) Dim formatter As New BinaryFormatter formatter.Serialize(fs, s3D.EncryptData(RichTextBox1.Rtf)) End Using End Sub Private Sub btn_LoadBinary_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles btn_LoadBinary.Click Dim dt As String = My.Computer.FileSystem.SpecialDirectories.Desktop Dim filePath As String = Combine(dt, "RTF.bin") Using fs As New FileStream(filePath, FileMode.Open) Dim formatter As New BinaryFormatter() RichTextBox1.Rtf = s3D.DecryptData(DirectCast(formatter.Deserialize(fs), String)) End Using End Sub End Class ''' <summary> ''' A class for simple encryption as per MSDN document shown at: ''' http://msdn.microsoft.com/en-us/library/ms172831(v=vs.90).aspx ''' </summary> ''' <remarks></remarks> Public NotInheritable Class Simple3Des Private TripleDes As New TripleDESCryptoServiceProvider Sub New(ByVal key As String) ' Initialize the crypto provider. TripleDes.Key = TruncateHash(key, TripleDes.KeySize \ 8) TripleDes.IV = TruncateHash("", TripleDes.BlockSize \ 8) End Sub Public Function EncryptData(ByVal plaintext As String) _ As String ' Convert the plaintext string to a byte array. Dim plaintextBytes() As Byte = _ System.Text.Encoding.Unicode.GetBytes(plaintext) ' Create the stream. Dim ms As New System.IO.MemoryStream ' Create the encoder to write to the stream. Dim encStream As New CryptoStream(ms, _ TripleDes.CreateEncryptor(), _ System.Security.Cryptography.CryptoStreamMode.Write) ' Use the crypto stream to write the byte array to the stream. encStream.Write(plaintextBytes, 0, plaintextBytes.Length) encStream.FlushFinalBlock() ' Convert the encrypted stream to a printable string. Return Convert.ToBase64String(ms.ToArray) End Function Public Function DecryptData(ByVal encryptedtext As String) _ As String ' Convert the encrypted text string to a byte array. Dim encryptedBytes() As Byte = Convert.FromBase64String(encryptedtext) ' Create the stream. Dim ms As New System.IO.MemoryStream ' Create the decoder to write to the stream. Dim decStream As New CryptoStream(ms, _ TripleDes.CreateDecryptor(), _ System.Security.Cryptography.CryptoStreamMode.Write) ' Use the crypto stream to write the byte array to the stream. decStream.Write(encryptedBytes, 0, encryptedBytes.Length) decStream.FlushFinalBlock() ' Convert the plaintext stream to a string. Return System.Text.Encoding.Unicode.GetString(ms.ToArray) End Function Private Function TruncateHash(ByVal key As String, _ ByVal length As Integer) _ As Byte() Dim sha1 As New SHA1CryptoServiceProvider ' Hash the key. Dim keyBytes() As Byte = _ System.Text.Encoding.Unicode.GetBytes(key) Dim hash() As Byte = sha1.ComputeHash(keyBytes) ' Truncate or pad the hash. ReDim Preserve hash(length - 1) Return hash End Function End Class


    Something to consider. :)


    Still lost in code, just at a little higher level.

    :-)

    • Marked as answer by Jason Bodine Monday, September 15, 2014 2:26 AM
    Friday, September 12, 2014 5:58 PM
  • Mr MonkeyBoy and Frank:

    Thanks!  I'll give both of these options a try and see what clicks! :)  My program, Personal Journal Editor, is an electronic diary program that I've been working on since the heyday of VB6, and like any good diary, you need the option of locking it up tight to protect the data, hence the encryption, lol!

    Jason

    Saturday, September 13, 2014 6:40 AM
  • Jason,

    Be aware you ask something about security. Given replies on that are like having 10 locks on your door with the 10 needed keys below the doormat before it. Everybody can find it on Internet.


    Success
    Cor


    • Edited by Cor Ligthert Saturday, September 13, 2014 8:51 AM
    Saturday, September 13, 2014 8:50 AM
  • @ Frank L. Smith:

    Your code isn't working. :(  Everything in the class is fine, but whenever I try to implement a new instance of it on the form, it says "Identifier expected."

    Jason

    Saturday, September 13, 2014 9:41 PM
  • @ Frank L. Smith:

    Your code isn't working. :(  Everything in the class is fine, but whenever I try to implement a new instance of it on the form, it says "Identifier expected."

    Jason

    Thanks for letting me know who you're addressing - many here don't - but please call me Frank. Seeing my full name gives me the willys. ;-)

    *****

    Will you show me the code where you're trying to use it please? Did you remember to include the Imports statements that I showed? It won't compile without those.


    Still lost in code, just at a little higher level.

    :-)

    Saturday, September 13, 2014 9:44 PM
  • @ Frank L. Smith:

    Your code isn't working. :(  Everything in the class is fine, but whenever I try to implement a new instance of it on the form, it says "Identifier expected."

    Jason

    Jason,

    Now that I think about it, the only class in there is one from Microsoft.

    When you instantiate it, you have to give it an encryption key. In my example I used the name of your assembly as shown here:

    Private s3D As New Simple3Des(My.Application.Info.AssemblyName)


    You can use any string (other than null or empty) of course, but it does have to have something to based the encryption on.


    Still lost in code, just at a little higher level.

    :-)

    Saturday, September 13, 2014 10:11 PM
  • @ Frank,

    I did.  I tried to set the key as the file's password from the database, and it still pulled that crap on me, lol.

    Moreover, the cryptography examples on MSDN aren't working either.  VB pitches a hellfire-and-brimstone hissyfit with the Rijndael example, saying it can't convert a string to a byte array. And VS2010 must have never even heard of AES because it throws all kinds of different errors at me with that one!

    *Groan* LOL

    Jason

    Saturday, September 13, 2014 10:39 PM
  • @ Frank,

    I did.  I tried to set the key as the file's password from the database, and it still pulled that crap on me, lol.

    Moreover, the cryptography examples on MSDN aren't working either.  VB pitches a hellfire-and-brimstone hissyfit with the Rijndael example, saying it can't convert a string to a byte array. And VS2010 must have never even heard of AES because it throws all kinds of different errors at me with that one!

    *Groan* LOL

    Jason

    That doesn't make sense - in either of those cases. I think there's something fundamental missing here.

    When you pass the string into the constructor, before you do that, can you confirm that the string returned from your database isn't null or empty?


    Still lost in code, just at a little higher level.

    :-)

    Saturday, September 13, 2014 10:44 PM
  • Jason,

    I recall you saying that you started this project in VB6. This now concerns me:

    How much (if any) did you "convert" from VB6 to VB Net?

    What dotNET framework are you targeting?

    That last point is of particular interest.


    Still lost in code, just at a little higher level.

    :-)

    Saturday, September 13, 2014 11:05 PM
  • Frank,

    Most of what I've had to convert involves moving from ADOX to ADO.NET, as I'm now on a 64-bit machine. I never had cryptography in any of the previous VB6 versions of the program. And, since I'm using VB 2010, I working with 4.0 .NET Framework.

    Here's the code from the dialog box that's doing the Encrypting and Decrypting.  I also plan on implementing it when the user actually opens a file.  To explain a little bit of what you're about to read, Reader is a class that stores all my access database values as properties; also the subs updating the database are in a separate module, and the blank If...Then....End If statement makes sure there's a file open to encrypt and is waiting for code that works to do it, lol.

        Private Sub chkEncrypt_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles chkEncrypt.CheckedChanged
            Active_Profile = GetSetting(Application.CompanyName, Application.ProductName, "Active_Profile")
            Dim DB As New Reader
            With DB
                .ProfileName = Active_Profile
                .File_Name = lblFile.Text
                If .FilePassword = "" Then
                    Dim Response As Windows.Forms.DialogResult = MessageBox.Show("You must set a password first!", Application.ProductName, MessageBoxButtons.OK)
                    If Response = Windows.Forms.DialogResult.OK Then
                        Exit Sub
                    End If
                ElseIf .FilePassword <> "" Then
                    Dim ChkPass As New frmPassword
                    ChkPass.Text = Application.ProductName
                    ChkPass.lblInstructions.Text = "Enter the password for " & Chr(34) & .FileName & "." & Chr(34)
                    If ChkPass.ShowDialog(Me) = Windows.Forms.DialogResult.OK Then
                        Dim Pwd As String = ChkPass.txtPassword.Text
                        ChkPass.Dispose()
                        If Pwd <> .FilePassword Then
                            MessageBox.Show("Incorrect password!", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                            DB.Dispose()
                            Exit Sub
                        Else
                            Dim attributes As System.IO.FileAttributes
                            If chkEncrypt.Checked = True Then
                                attributes = IO.FileAttributes.Encrypted
                                UpdateFileBoolean("Is_Encrypted", True, .FileName, .ProfileName)
                                System.IO.File.Encrypt(OpenedFile)
                                System.IO.File.SetAttributes(OpenedFile, attributes)
                                Dim Child As Form = frmMain.ActiveMdiChild
                                If Not IsNothing(Child) AndAlso TypeOf Child Is frmDocument Then
                                    Dim rtfDocument As RichTextBox = TryCast(Child.ActiveControl, RichTextBox)
                                    If Not IsNothing(rtfDocument) Then
                                       
    
                                    End If
                                End If
                            Else
                                attributes = IO.FileAttributes.Normal
                                UpdateFileBoolean("Is_Encrypted", False, .FileName, .ProfileName)
                                System.IO.File.Decrypt(OpenedFile)
                                System.IO.File.SetAttributes(OpenedFile, attributes)
                            End If
                        End If
                    Else
                        DB.Dispose()
                        Exit Sub
                    End If
                End If
            End With
        End Sub

    EDIT: The rest of the code executes like it is supposed to, so it is definitely not returning a null or empty string.

    Jason


    Sunday, September 14, 2014 5:28 AM
  • Jason,

    I don't see anywhere in there where you're using anything that I showed the other day. Did you decide against using it?

    If you want, I'll zip up the example project and upload it so you can test that by itself.


    Still lost in code, just at a little higher level.

    :-)

    Sunday, September 14, 2014 11:51 AM
  • Frank,

    Yours is still the code I'm leaning towards, *if* I can make it work, lol.  :)  I removed the code to try a couple of other things, which is why it isn't there right now.  I'm about to try it in a module instead of a class and see if that makes any difference.  I'll let you know! :)

    Jason

    Sunday, September 14, 2014 12:12 PM
  • Frank,

    Yours is still the code I'm leaning towards, *if* I can make it work, lol.  :)  I removed the code to try a couple of other things, which is why it isn't there right now.  I'm about to try it in a module instead of a class and see if that makes any difference.  I'll let you know! :)

    Jason

    Try this, just on its own, for the sake of elimination of the problem:

    http://www.fls-online.com/VBNet_Forum/09-14-14/Test_SerializeRTB_Data.zip

    That's a zip file of the project. Download that and extract it somewhere then open the solution. It will prompt you to upgrade it because it's done in VS 2008 but just follow the prompts and it should convert without a problem.


    Still lost in code, just at a little higher level.

    :-)

    Sunday, September 14, 2014 12:16 PM
  • Ok.... The code in your project worked as a standalone.

    I tried it as a module in mine and while it didn't throw any errors, it also didn't *do* anything, lol.

    Here's the module code:

    Imports System.IO
    Imports System.IO.Path
    Imports System.Runtime.Serialization.Formatters.Binary
    Imports System.Security.Cryptography
    Module Crypto
        Public TripleDES As New TripleDESCryptoServiceProvider
        Public Sub Create(key As String)
            TripleDES.Key = TruncateHash(key, TripleDES.KeySize \ 8)
            TripleDES.IV = TruncateHash("", TripleDES.BlockSize \ 8)
        End Sub
        Public Function EncryptData(ByVal plaintext As String) _
           As String
    
            ' Convert the plaintext string to a byte array. 
            Dim plaintextBytes() As Byte = _
                System.Text.Encoding.Unicode.GetBytes(plaintext)
    
            ' Create the stream. 
            Dim ms As New System.IO.MemoryStream
            ' Create the encoder to write to the stream. 
            Dim encStream As New CryptoStream(ms, _
                TripleDes.CreateEncryptor(), _
                System.Security.Cryptography.CryptoStreamMode.Write)
    
            ' Use the crypto stream to write the byte array to the stream.
            encStream.Write(plaintextBytes, 0, plaintextBytes.Length)
            encStream.FlushFinalBlock()
    
            ' Convert the encrypted stream to a printable string. 
            Return Convert.ToBase64String(ms.ToArray)
        End Function
    
        Public Function DecryptData(ByVal encryptedtext As String) _
            As String
    
            ' Convert the encrypted text string to a byte array. 
            Dim encryptedBytes() As Byte = Convert.FromBase64String(encryptedtext)
    
            ' Create the stream. 
            Dim ms As New System.IO.MemoryStream
            ' Create the decoder to write to the stream. 
            Dim decStream As New CryptoStream(ms, _
                TripleDes.CreateDecryptor(), _
                System.Security.Cryptography.CryptoStreamMode.Write)
    
            ' Use the crypto stream to write the byte array to the stream.
            decStream.Write(encryptedBytes, 0, encryptedBytes.Length)
            decStream.FlushFinalBlock()
    
            ' Convert the plaintext stream to a string. 
            Return System.Text.Encoding.Unicode.GetString(ms.ToArray)
        End Function
    
        Private Function TruncateHash(ByVal key As String, _
                                      ByVal length As Integer) _
                                      As Byte()
    
            Dim sha1 As New SHA1CryptoServiceProvider
    
            ' Hash the key. 
            Dim keyBytes() As Byte = _
                System.Text.Encoding.Unicode.GetBytes(key)
            Dim hash() As Byte = sha1.ComputeHash(keyBytes)
    
            ' Truncate or pad the hash. 
            ReDim Preserve hash(length - 1)
            Return hash
        End Function
    End Module
    


    and here's the code in the form:

     
      Private Sub chkEncrypt_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles chkEncrypt.CheckedChanged
            Active_Profile = GetSetting(Application.CompanyName, Application.ProductName, "Active_Profile")
            Dim DB As New Reader
            With DB
                .ProfileName = Active_Profile
                .File_Name = lblFile.Text
                If .FilePassword = "" Then
                    Dim Response As Windows.Forms.DialogResult = MessageBox.Show("You must set a password first!", Application.ProductName, MessageBoxButtons.OK)
                    If Response = Windows.Forms.DialogResult.OK Then
                        Exit Sub
                    End If
                ElseIf .FilePassword <> "" Then
                    Dim ChkPass As New frmPassword
                    ChkPass.Text = Application.ProductName
                    ChkPass.lblInstructions.Text = "Enter the password for " & Chr(34) & .FileName & "." & Chr(34)
                    If ChkPass.ShowDialog(Me) = Windows.Forms.DialogResult.OK Then
                        Dim Pwd As String = ChkPass.txtPassword.Text
                        ChkPass.Dispose()
                        If Pwd <> .FilePassword Then
                            MessageBox.Show("Incorrect password!", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                            DB.Dispose()
                            Exit Sub
                        Else
                            Dim attributes As System.IO.FileAttributes
                            If chkEncrypt.Checked = True Then
                                attributes = IO.FileAttributes.Encrypted
                                UpdateFileBoolean("Is_Encrypted", True, .FileName, .ProfileName)
                                System.IO.File.Encrypt(OpenedFile)
                                System.IO.File.SetAttributes(OpenedFile, attributes)
                                Dim Child As Form = frmMain.ActiveMdiChild
                                If Not IsNothing(Child) AndAlso TypeOf Child Is frmDocument Then
                                    Dim rtfDocument As RichTextBox = TryCast(Child.ActiveControl, RichTextBox)
                                    If Not IsNothing(rtfDocument) Then
                                        Create(.FilePassword)
                                        EncryptData(rtfDocument.Text)
                                        rtfDocument.SaveFile(OpenedFile)
                                        Child.Refresh()
                                    End If
                                End If
                            Else
                                attributes = IO.FileAttributes.Normal
                                UpdateFileBoolean("Is_Encrypted", False, .FileName, .ProfileName)
                                System.IO.File.Decrypt(OpenedFile)
                                System.IO.File.SetAttributes(OpenedFile, attributes)
                                Dim Child As Form = frmMain.ActiveMdiChild
                                If Not IsNothing(Child) AndAlso TypeOf Child Is frmDocument Then
                                    Dim rtfDocument As RichTextBox = TryCast(Child.ActiveControl, RichTextBox)
                                    If Not IsNothing(rtfDocument) Then
                                        Create(.FilePassword)
                                        DecryptData(rtfDocument.Text)
                                        rtfDocument.SaveFile(OpenedFile)
                                        Child.Refresh()
                                    End If
                                End If
                            End If
                        End If
                    Else
                        DB.Dispose()
                        Exit Sub
                    End If
                End If
            End With
        End Sub
    Jason
    Sunday, September 14, 2014 12:45 PM
  • Jason,

    You don't need that to be in a module - that's like having a shared class (no such animal in VB) so that it's never out-of-scope. I don't see any benefit in that at all.

    *****

    I'm not going to pretend that I'm following your code, but you said that as a standalone it works, so we know that's not the issue.

    Put a breakpoint in and start stepping through the code and inspect the variables at each step. That should lead you to where things are going awry.

    *****

    If you haven't already, please put the following at the very top of your form:

    Option Strict On
    Option Explicit On
    Option Infer Off


    Still lost in code, just at a little higher level.

    :-)

    Sunday, September 14, 2014 12:49 PM
  • Frank,

    I'm not exactly sure what I did wrong before, but it's working now! LOL :)  Thanks much!!!

    Jason

    Monday, September 15, 2014 2:27 AM
  • Frank,

    I'm not exactly sure what I did wrong before, but it's working now! LOL :)  Thanks much!!!

    Jason


    I'm glad you got it working. :)

    Still lost in code, just at a little higher level.

    :-)

    Monday, September 15, 2014 1:58 PM
  • Just one more related question... how do I get it to encrypt/decrypt images and write them to the file too?

    This little bit of code:

       Dim plaintext As String = Form2.rtfDocument.Text
                                                Dim password As String = .FilePassword
                                                Dim wrapper As New Cryptography(password)
                                                Dim cyphertext As String = wrapper.EncryptData(plaintext)
                                                My.Computer.FileSystem.WriteAllText(OpenedFile, cyphertext, False)

    Writes the encrypted text to the file when you click on Save in the menu, but if you have any images in the file, when you open it again, they've gone *poof!* lol

    Here's the encryption/decryption code:

    Imports System.Security.Cryptography
    Public NotInheritable Class Cryptography
        Private TripleDes As New TripleDESCryptoServiceProvider
        Private Function TruncateHash(
        ByVal key As String,
        ByVal length As Integer) As Byte()
    
            Dim sha1 As New SHA1CryptoServiceProvider
    
            ' Hash the key. 
            Dim keyBytes() As Byte =
                System.Text.Encoding.Unicode.GetBytes(key)
            Dim hash() As Byte = sha1.ComputeHash(keyBytes)
    
            ' Truncate or pad the hash. 
            ReDim Preserve hash(length - 1)
            Return hash
        End Function
        Sub New(ByVal key As String)
            ' Initialize the crypto provider.
            TripleDes.Key = TruncateHash(key, TripleDes.KeySize \ 8)
            TripleDes.IV = TruncateHash("", TripleDes.BlockSize \ 8)
        End Sub
        Public Function EncryptData(
        ByVal plaintext As String) As String
    
            ' Convert the plaintext string to a byte array. 
            Dim plaintextBytes() As Byte =
                System.Text.Encoding.Unicode.GetBytes(plaintext)
    
            ' Create the stream. 
            Dim ms As New System.IO.MemoryStream
            ' Create the encoder to write to the stream. 
            Dim encStream As New CryptoStream(ms,
                TripleDes.CreateEncryptor(),
                System.Security.Cryptography.CryptoStreamMode.Write)
    
            ' Use the crypto stream to write the byte array to the stream.
            encStream.Write(plaintextBytes, 0, plaintextBytes.Length)
            encStream.FlushFinalBlock()
    
            ' Convert the encrypted stream to a printable string. 
            Return Convert.ToBase64String(ms.ToArray)
        End Function
        Public Function DecryptData(
        ByVal encryptedtext As String) As String
    
            ' Convert the encrypted text string to a byte array. 
            Dim encryptedBytes() As Byte = Convert.FromBase64String(encryptedtext)
    
            ' Create the stream. 
            Dim ms As New System.IO.MemoryStream
            ' Create the decoder to write to the stream. 
            Dim decStream As New CryptoStream(ms,
                TripleDes.CreateDecryptor(),
                System.Security.Cryptography.CryptoStreamMode.Write)
    
            ' Use the crypto stream to write the byte array to the stream.
            decStream.Write(encryptedBytes, 0, encryptedBytes.Length)
            decStream.FlushFinalBlock()
    
            ' Convert the plaintext stream to a string. 
            Return System.Text.Encoding.Unicode.GetString(ms.ToArray)
        End Function
    End Class
    

    Jason



    • Edited by Jason Bodine Monday, September 15, 2014 11:31 PM
    Monday, September 15, 2014 11:27 PM
  • You didn't ask about that in your original question. Images are not the same as text so the requirement is different just as it is with encrypting or decrypting most non text.

    La vida loca

    Tuesday, September 16, 2014 12:58 AM
  • @ Mr. Monkeyboy

    Ok, but to be fair, lol, I am new to encryption and your original reply did include a graphic in the RichTextBox, so I didn't know *to* include that in the question. :)

    So how do I go about encrypting the whole kit and kaboodle, then?

    Jason

    Tuesday, September 16, 2014 2:22 AM
  • Just one more related question... how do I get it to encrypt/decrypt images and write them to the file too?

    Jason,

    Do you mean images embedded in the RTF or something else?

    There are some obstacles (like an OOM Exception) which have to be overcome. It's not the what, it's the why, so we'll have to contrive a way that doesn't use the standard means. I'll explain more when you reply back.

    *****

    I'm more and more confused about your program though. What is the purpose of the database?

    Explain, if you will, what your program is and does. Not in "code talk", just plain talk. The elevator speech, so to speak.


    Still lost in code, just at a little higher level.

    :-)

    Tuesday, September 16, 2014 1:24 PM
  • @ Frank L. Smith

    The program is called Personal Journal Editor.  It's an electronic diary program that--as of this version--supports multiple user profiles and has security features, like using the webcam to take a picture and either email, text, or mms it to the profile's owner or the creator of a file if the wrong password is entered and the user has all the settings set up for it to do so.  That's what the database is for, storing all the user's preferences (like whether or not to display the toolbar, what picture, if any, to use as the main form's background image, etc.) as well as information about files like the file's password, whether or not it is encrypted or read-only.  Stuff like that. :)

    As for the images in the Richtextbox, the user can paste images into it, so I guess they're embedded, and I figure that if a use wants to encrypt his files, he or she might want to encrypt the whole thing, including the images lol.

    If you would like, I can put my project on my OneDrive account and link you to it so you can see what's going on with it, lol

    Jason

    Tuesday, September 16, 2014 4:10 PM
  • Jason,

    Please call me Frank. Seeing my whole name (other than by me) reminds me of being in the third grade and being called to the principal's office! ;-)

    *****

    The issue will be total memory consumption and that's what I meant earlier about the "how". It doesn't stream anything - it loads the entire thing into memory and then writes it out to file. If there's not enough memory then obviously it never gets to the second part because an OutOfMemoryException is thrown.

    As a whole other way of doing this, consider a method which doesn't do things like that - for example, zipping the file into a password-protected file. No encrypting, no serialization - just use the password-protection built into it.

    Your thoughts?


    Still lost in code, just at a little higher level.

    :-)

    Tuesday, September 16, 2014 4:18 PM
  • Frank,

    I thought about doing it that way, with the zip files. But went with this method instead because, 1) I figured it was about time I learned to do it, and 2) something about the idea of outsmarting a snooper who thinks to try to look at the contents of a file by opening it in Wordpad or notepad or what have you just makes me feel all warm and fuzzy inside, lol! :)

    Jason

    Tuesday, September 16, 2014 4:34 PM
  • Frank,

    I thought about doing it that way, with the zip files. But went with this method instead because, 1) I figured it was about time I learned to do it, and 2) something about the idea of outsmarting a snooper who thinks to try to look at the contents of a file by opening it in Wordpad or notepad or what have you just makes me feel all warm and fuzzy inside, lol! :)

    Jason

    There are other ways it could be done and one that comes to mind would be something along the lines of what I posted a few weeks ago shown here.

    Have a look at what (and HOW) I'm splitting the file into "file blocks" in that.


    Still lost in code, just at a little higher level.

    :-)

    Tuesday, September 16, 2014 4:38 PM
  • Frank,

    I thought about doing it that way, with the zip files. But went with this method instead because, 1) I figured it was about time I learned to do it, and 2) something about the idea of outsmarting a snooper who thinks to try to look at the contents of a file by opening it in Wordpad or notepad or what have you just makes me feel all warm and fuzzy inside, lol! :)

    Jason

    That's a lot to take in just to get to the essence of it, so let me summarize:

    Option Strict On Option Explicit On Imports System.IO Imports System.IO.Path Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles MyBase.Load Dim filePath As String = _ Combine(My.Computer.FileSystem.SpecialDirectories.Desktop, _ "Update_08-25-14.docx") Using fs As New FileStream(filePath, FileMode.Open) While fs.Position < fs.Length Dim byteLength As Integer = 1024 * 1024 If fs.Length - fs.Position < byteLength Then byteLength = CInt(fs.Length - fs.Position) - 1 End If Dim bytes(byteLength) As Byte fs.Read(bytes, 0, bytes.Length) Stop End While End Using End Sub End Class


    I'm giving it the file path of an MS Word file that I put on my desktop. I then create a filestream in a Using block.

    Using fs As New FileStream(filePath, FileMode.Open)

    Nothing has yet been done to the file or the filestream, it's just telling it what you want.

    While fs.Position < fs.Length

    In a while loop I have it looking at the position - the "pointer" - and continue to perform the code that's in the while loop until the position of that pointer is no longer less than the length. In other words, "do this until you're at the end of the stream".

    Dim byteLength As Integer = 1024 * 1024

    In that I tell it how much I want to read (done later) - one meg.

    If fs.Length - fs.Position < byteLength Then
        byteLength = CInt(fs.Length - fs.Position) - 1
    End If

    Before the rest is evaluated it's likely that the file's length won't be EXACTLY in one meg increments so that last bunch of bytes is probably less then the originally declared length. That part just shown readjusts the length to read (done later).

    Dim bytes(byteLength) As Byte

    That declares a variable (that I'm calling "bytes") which is a byte array and it's given the length that I defined earlier. Still nothing has been done with the file or the stream at this point.

    fs.Read(bytes, 0, bytes.Length)

    NOW the file is read - from wherever the position was to the length that I defined earlier.

    ONLY THAT LENGTH is loaded into memory.

    In my "file splitter" I'm writing that out to a file (that I call a "file block"), but at this point in time, you can then do something with that filestream using a similar technique. The most that's loaded into memory is whatever you've told it to read.

    Make sense?


    Still lost in code, just at a little higher level.

    :-)

    Tuesday, September 16, 2014 5:13 PM
  • For clarification, what I just said about only that length being in memory, that's not so.

    The byte array created is now out of scope (per loop) which means that it's then eligible for the GC to attend to it, but it's up to the GC to do that. So I should have said that, but effectively only that byte array is in scope and is "live" in memory.


    Still lost in code, just at a little higher level.

    :-)

    Tuesday, September 16, 2014 5:23 PM
  • Frank,

    Something just occurred to me, but I'm not quite sure how to implement it since the images in the rtf files are data from the clipboard pasted into the richtextbox, rather than a file with a path that you can just call some enrypting routine for: What about converting the bytes in the rtf file that are image data into base 64 strings before encryption so that the encryption algorithm now only has text to deal with, and then converting them back into image format when the file is decrypted?

    Is there a way to do that?

    Jason

    Wednesday, September 17, 2014 6:25 AM
  • Frank,

    Something just occurred to me, but I'm not quite sure how to implement it since the images in the rtf files are data from the clipboard pasted into the richtextbox, rather than a file with a path that you can just call some enrypting routine for: What about converting the bytes in the rtf file that are image data into base 64 strings before encryption so that the encryption algorithm now only has text to deal with, and then converting them back into image format when the file is decrypted?

    Is there a way to do that?

    Jason

    I think you're moving the wrong direction, honestly.

    Here's a test that I just did. I created a new .rtf file and just typed in a short sentence, saved it, then look at it in explorer:

    Pretty small, certainly easily handled. Next I added a .png image. The image is only 15K (it's a screenshot). Not much difference to the .rtf file, right?

    Oh yes there sure is a lot of difference! So how did adding a 15K image in there end up being nearly 7 megs?

    There's the image that I added - in "RTF" terms.

    I want to show you one more thing though:

    Compression really makes a difference. So what does that .zip file look like on the inside:

    It looks like that all the way down.

    I really do think that's the better solution here.


    Still lost in code, just at a little higher level.

    :-)

    Wednesday, September 17, 2014 1:48 PM
  • Frank,

    I see your point!  So how do I go about doing that, then?  I've seen tutorials online, but they all involved 3rd-party controls.

    Thanks,

    Jason :)

    Thursday, September 18, 2014 5:30 AM
  • Frank,

    I see your point!  So how do I go about doing that, then?  I've seen tutorials online, but they all involved 3rd-party controls.

    Thanks,

    Jason :)


    You might look at the System.IO.Compression namespace but I've never worked with it. I have had a little practice (albeit a long time back) with this third-party one and from what I recall, it seemed to work ok.

    Still lost in code, just at a little higher level.

    :-)

    Thursday, September 18, 2014 9:57 AM
  • @Frank,

    This is turning out to be a royal pain and a half, lol!  Encrypting Zip Files is *way* over my head.  :( How about just converting the whole file into a byte array and encrypting/decrypting it?  

    Jason

    Friday, September 19, 2014 5:37 AM
  • @Frank,

    This is turning out to be a royal pain and a half, lol!  Encrypting Zip Files is *way* over my head.  :( How about just converting the whole file into a byte array and encrypting/decrypting it?  

    Jason


    This thread has really been worn out with changes in direction. How about start a new question please (but I wouldn't bother with it - password protection for the zip file really should be sufficient).

    Still lost in code, just at a little higher level.

    :-)

    Friday, September 19, 2014 11:17 AM