Click here to Skip to main content
Click here to Skip to main content
Go to top

Encrypting Editor Notepad replacement

, 8 Jul 2013
Rate this:
Please Sign up or sign in to vote.
A C# .Net 3.5 Windows Forms Application with source code.
This is an old version of the currently published article.

Introduction

I love Windows Notepad! I write all my HTML, Jscript, CMD scripts, and much more in Notepad. It is my favorite editing tool. It is fast and simple. So, why would I write a replacement program?

The primary purpose of the CryptPad program is to provide optional file encryption. This is valuable for files which contain sensitive information. Unlike many other encryption solutions, this one only encrypts and decrypts one file at save and open. There is never a decrypted version of the file stored unless the operator (I am a little uncomfortable with the word "user") specifies to remove the encryption. The file can be stored multiple places and moved freely, but always in encrypted form. Anyone who knows the encryption string can read the file with this program.

Because of the importance of maintaining multiple passwords for better security, I have a file with all the passwords in it that I use. This is also a security risk unless the file is encrypted. I have examined many encryption solutions and none does exactly what I need. I need to be able to transport and store an encrypted file anywhere I want. Encrypted drives are not what I need. The file must never exist in decrypted form. Therefore I need a simple editor which opens, decrypts, edits, encrypts, and saves a file.

Notice that I do not at any point describe CryptPad as a Notepad clone. A clone is an exact copy. Notepad has some very specific functionality, which I have seen nobody duplicate completely. For example, the Undo function of Notepad has not been fully implemented in most advertised "clones". I have also not seen a "clone" which properly implements UTF-8 and Unicode conversions or reads files with ANSI characters as Notepad and CryptPad do.

CryptPad is intended to be nearly the same as Windows 7 Notepad. I have chosen not to include some functions which I do not consider useful or important such as printing. I almost never use paper or printing! CryptPad is not a "clone" but is close enough to be a useful replacement. Now that I have the source code for a replacement for Notepad, I have been adding functions useful in my daily editing.

I also have a major problem with Notepad because it allows a problem called parallel update. Unlike Notepad, CryptPad maintains the file in an opened state locked against parallel changes but shared with file readers. This protects the file against accidental parallel modification data loss problems. I have had this happen to me on occasion with Notepad. You can still lose changes but it will have to be by deliberate actions and not by casual accident.

I hope you find the CryptPad program useful. I am interested in any problems you may find in the program and in particular any incompatibility as a Notepad replacement. I am also interested in your ideas about improving this simple program. I intend to keep the program as small and simple as practical. CryptPad will always be a switchblade not a Swiss Army knife.

I continue to use, modify, and test the CryptPad program. I will return periodically (about once a month or so) to update this article and the source code.

ASCII, ANSI, UTF-8

In the old days of microcomputers (about 1980), it was simple. (It wasn't really, but we will pretend it was.) All text files were 7 bit ASCII (American Standard Code for Information Interchange) characters. Notice the word "American" in ASCII. There are many people in the world, with many different languages and characters, and they need to be represented in daily computer use. There are also additional "American" characters in common use beyond plain ASCII.

There is a great deal of confusion about the subject of character encoding. If you are a detail oriented person and prepared for a heavy read, you can start here:

http://en.wikipedia.org/wiki/UTF-8

I will try to make it short and simple. When you are using typical ASCII characters, strict UTF-8 (without BOM) is exactly the same thing. Most of your editing will be simple ASCII. This entire webpage is only ASCII. In most cases, you can just stop here.

The exception is if you ever use characters such as Microsoft Word smart quotes and apostrophes. These are the "curved" typographical equivalents of the simple "straight" ASCII quote and apostrophe. The apostrophe has a curve and there is a different curve for beginning and ending a quote. There are many other types of special characters.

There are two primary ways to represent these types of non-ASCII characters. The older way is with 8 bit characters. This is when you see "Windows-1252" or other non-Unicode encodings. These encodings can be very complex and plagued with limitations. Notepad refers to this as "ANSI" encoding. Unicode makes the process simpler (but not simple) to support everybody's characters. UTF-8 was invented to support ASCII with no changes and optionally extend to Unicode characters.

If this short explanation made you curious to know more, then you are back to the heavy reading I mentioned earlier.

Installing the Program

Program installation is recommended for a CryptPad directory under the Documents directory for an individual operator. The Program files directory can be used for an administrator install for all operators. "Open With" can be set to default to CryptPad for the .SAFE encrypted files created by CryptPad. The program is completely stand-alone so a simple copy is all that is needed to install. You can carry it on a USB stick and use anywhere.

I do not provide an install program because I want you to know for absolute certain exactly what is required to use the program. Uninstall is very simple. Erase the program! Setup programs mysteriously make unknown changes to your computer. I won't even change the registry for you. I provide the complete source so you can know for certain exactly what the program does. Compile it for yourself, if you are able. Examining the code is not easy but it is available, if it is a concern to you. By these methods, you can trust the software. There is so much out there that is not trustworthy. You don't have to trust me. Full disclosure is the best trust there is.

If you wish the .SAFE file to be opened automatically by CryptPad, then you will need to choose CryptPad as the default program using "Open With". You might choose to set the default "Open With" to CryptPad for .TXT also to take advantage of the additional editing functions. A REG file is provided which contains all kinds of settings I use to make CryptPad the default editor. These have been used and tested on Windows 7. I now use CryptPad to edit everything where I would have used Notepad. For other registry changes I used the "Default Programs Editor" freeware download, which works great. It is highly recommended.

The program is compiled with the .NET framework version 3.5, which is included automatically with the Windows 7 OS. The program has only been well used and thoroughly tested with the Windows 7 OS.

The program has only been used a little with the Windows 8 OS (Yuck!). Maybe Windows 8.1 will be better...

The program has not been used or tested with Windows Vista (another Yuck!) or XP. Unfortunately, the .NET framework version 3.5 is not installed in Windows Vista or XP so you will need to install it to use the program in Windows Vista or XP. There are likely to be issues with the program. I don't use Windows Vista or XP anymore so I won't be able to help you.

Using the Program

Perhaps it will be helpful for me to give a step by step procedure for creating an encrypted file.
  1. Start the CryptPad program.
  2. Enter your data.
  3. Select File, Encryption
  4. Enter your encryption string and type the Enter key.
  5. Enter the same encryption string again and type the Enter key.
  6. Save your file.
  7. If you open the encrypted file in Notepad you will see "~!@#" and more nonsense characters. Close the file without making any changes.
  8. Open the encrypted file in CryptPad.
  9. Enter your encryption string and type the Enter key.
  10. There is your data...

I hope this brief description helps. The installation and use of this program is NOT designed for the casual or novice operator! If you follow the instructions carefully, you will be able to install and use the program.

Using the Code

I am providing the complete VS2010 C# project zip file with the executable and the complete source code for CryptPad, the encrypting editor Notepad replacement program for those who enjoy software code. You might be interested in adding your own special functionality.

I hope you find the source code instructive for picking up some ideas. I have learned a lot by examining the code of others. I hope examining my code will be useful to you.

The project contains numerous test files and various things I found useful to develop, test, and use CryptPad. Of particular interest are the "CryptPad (Readonly)" and the "SendTo" shortcuts. Clicking the "SendTo" shortcut opens the directory where these shortcuts reside. You can drag and drop the "CryptPad (Readonly)" shortcut on the "SendTo" shortcut to add a new item. There are many interesting and useful things you can do with the "SendTo" directory.

Points of Interest

One of the many interesting features in the program source code is the automatic detection of ANSI, UTF-8, and Unicode character encodings with Byte Order Mark (BOM) detection. This is the feature missing out of all Notepad "clones" I have seen. One of them implements it now because I told the writer how to do it. The .NET library provides all the support needed for automatic detection but doesn't tell you how to use it.

There are two pieces of information required and some sample code to demonstrate their use. I have seen many complicated solutions proposed for automatic detection but it is actually quite simple. I will mention that my assumption is that the file is properly encoded without encoding errors or malformed characters. This is a reasonable assumption for any properly written program (such as Notepand and CryptPad) used to create a file.

The first piece of necessary information is to recognize that the UTF-8 encoding has been carefully designed for automatic detection, which makes it vastly different than the complexities and ambiguities of ANSI encoding. It is highly unlikely (but possible) that an ANSI file would be mistaken as UTF-8. The other detection methods don't promise any better. I won't go into detail about this feature of the UTF-8 encoding.

The second piece of necessary information is to recognize that the .NET library implements automatic detection through exception handling when ANSI characters are found. Unfortunately, the documentation doesn't connect the dots for how to implement this automatic detection.

This sample code illustrates automatic detection of UTF-8 and other Unicode encodings with an exception handling fallback to ANSI encoding.

This simple example excerpt is not identical to the supplied source code.

file_stream = new FileStream (filename, FileMode.Open,
    FileAccess.ReadWrite, FileShare.Read);

// UTF-8 encoding with automatic dection of other
// Unicode encodings and ANSI error detection
Encoding save_encoding = new UTF8Encoding (false,true);
StreamReader sr = new StreamReader (file_stream,
    save_encoding, true);

string str = null;
try
{
    str = sr.ReadToEnd ();
    // Save the actual encoding for later write
    save_encoding = sr.CurrentEncoding;
}
catch
{
    // ANSI error detection
    save_encoding = null;
}
if (null == save_encoding)
{
    // use ANSI from the default code page
    save_encoding = Encoding.GetEncoding (0);
    file_stream.Position = 0;
    sr = new StreamReader (file_stream, save_encoding);
    str = sr.ReadToEnd ();
}

... modify str

// discard any previous contents
file_stream.SetLength (0);

// use StreamWriter with the same encoding
StreamWriter sw = new StreamWriter (file_stream,
    save_encoding);
sw.Write (str);

The most novel aspect of the program source code is the encryption. The program uses a quick and simple scrambling algorithm of addition/subtraction based on a secret encryption string provided by the operator. The program encrypts only ASCII so that I have a contiguous arithmetic range. My apologies to those whose language is not based on ASCII. The intent is to continue to use text rather than binary processing. The encryption is highly efficient and adds only 21 bytes to the size.

These simple example excerpts are not identical to the supplied source code.

private string Encrypt (string str)
{
    StringBuilder st = new StringBuilder (str);
    for (int i = 0; i < st.Length; ++i)
    {
        int chr = st[i];
        if (isASCII ((char) chr))
        {
            chr = ' ' + ((E (i) + (chr - ' ')) % 95);
            st[i] = (char) chr;
        }
    }
    return st.ToString ();
}

private string Decrypt (string str)
{
    StringBuilder st = new StringBuilder (str);
    for (int i = 0; i < st.Length; ++i)
    {
        int chr = st[i];
        if (isASCII ((char) chr))
        {
            chr = ' ' + ((chr - 32) - E (i) + 95) % 95;
            st[i] = (char) chr;
        }
    }
    return st.ToString ();
}

The encryption string is scrambled with a pseudo-random number seeded with a checksum of the encryption string

private int E (int i)
{
return (encryption_string[i % encryption_string.Length]
    + i + i * random_seed) % 95;
}

// plus checksum for random_seed
private int ChecksumAdd (string str)
{
    int checksum = 0;
    for (int i = 0; i < str.Length; ++i)
    {
        checksum += str[i];
    }
    return checksum;
}

The program uses an additional XOR checksum placed in the file to verify whether the encryption string is correct when attempting to decrypt. I protect short encryption strings by extending it to at least 32 characters.

// xor checksum for in the file
private uint ChecksumXOR (string str)
{
    uint checksum = 0;
    int j = 32;
    if (32 < str.Length)
        j = str.Length;
    for (int i = 0; i < j; ++i)
    {
        uint t = 0;
        if (0 < (0x80000000 & checksum))
            t = 1;
        checksum <<= 1;
        checksum |= t;
        checksum ^= str[i % str.Length];
    }
    return checksum;
}

I use a second similar checksum to detect whether the encrypted data has been corrupted by being modified without being decrypted. This would destroy the integrity of the encrypted data. The operator would be warned immediately upon attempting to open the file whether the encrypted data had been modified and corrupted.

I would not claim the encryption used by this program is CIA quality but I think you will find it is highly effective. The strength of the encryption is highly dependent on the length of the encryption string. A strong string of ten characters or more is not likely to be broken by anyone except a skilled cryptologist. I am not a skilled cryptologist but I am familiar with some aspects of cryptology. The primary attacks against this encryption have been anticipated.

I have thought about offering a challenge to see if a clever hacker or skilled cryptologist would take an interest and break it. I would be interested to know how long it took, what type of equipment was needed, and what attack vector succeeded.

The most likely attack would be against the XOR checksum used to verify the encryption string against typographical error. The succes of this type of attack depends on the strength of the encryption string you choose.

Release History and Notes

A history of changes to the CryptPad program and release notes.
  • Version 2.0 released 2013-07-07:
    • Revised and continued adding Command Line Automation functions.
    • Added a Command Line function to display the command line arguments provided at program startup. This is useful in debugging Command Line Automation functions.
    • Added a second XOR checksum to detect and warn whether the encrypted data has been improperly modified or corrupted. If you have used CryptPad to make important encrypted files in an earlier version, you need to be aware there is an automatic file conversion which makes a version 2 encrypted file incompatible with earlier versions. If you need to know, you can remove character 5 ('$') and 6-13 (hexadecimal checksum) to restore version 1 compatibility.
    • Replaced MessageBox, which centers on the screen instead of the parent window, for all popup message functions. All popup messages will now appear in the center of the CryptPad window. This was implemented as a simple single file class, which can be easily used in other programs.
    • I changed the meaning of Find Next (F3) to always use direction down and added a Find Previous (Shift-F3) to use direction up. I am familiar with these assignments from other programs. I hope it is not a problem for others.
    • Added the Automatic Backup option.
  • Version 1.11 released 2013-06-16:
    • Adding Command Line Automation functions.
    • Added an option to force UTF-8 (ASCII) encoding before the file is written.
    • Changed "Company" reference from Keep It Simple Software to Frank T Clark Software because there is already a registered company by that name. Settings are tied to the company name so the previous settings are lost. They may be retrieved by copying the user.config file from the C:\Users\%username%\AppData\Local\Keep_It_Simple_Software\... directory but this is not obvious or simple.
    • Changed "Copyright" reference to a Published/Revised date.
    • Fixed initialization on Windows Position to allow the settings to be remembered.
    • Improved dangling CR or LF detection.
    • Fixed error with Cancel of Save not returning to document modifications as it should. I lost some work! (Heavy sigh...)
  • Version 1.10 released 2013-05-14:
    • Problem with settings being saved too often leading to a conflict when two files opened at the same time.
    • Caret moved to the top after Replace All.
    • A warning is given on file open if a dangling CR or LF is seen outside of a CR/LF pair.
    • Added "Force CR/LF (Windows)", "Force LF (UNIX)", and "Mark dangling CR or LF" to the Tools menu.
    • Fixed unescape of backslash sequences for Find and Replace.
    • I discovered Notepad changes NUL characters to spaces or the textbox will not work!
  • Version 1.9 released 2013-04-18:
    • Major code review and revise.
    • Improved graphics and icon modified from Notepad.
    • Fixed find direction up.
    • Fixed some missing Verdana 12pt settings.
    • Discard previous file completely at Open of a new file.
    • Replace All was too slow and would not undo all so changed to match Notepad.
    • Improved all Undo function to match Notepad.

You may refer to the help/documentation provided with the source or the original website for additional details about the CryptPad program:

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Frank T. Clark
Systems Engineer Three Angels Broadcasting Network
United States United States
I am a Software Systems Design Engineer experienced with IEEE standards and the entire IEEE software development life cycle. Concept Exploration, Requirements, Design, Implementation, Test, Installation and Checkout, Operation and Maintenance. I enjoy working with people and solving customer problems.
 
I am currently employed as Information Technology Staff in the religious satellite broadcasting industry.

Comments and Discussions


Discussions posted for the Published version of this article. Posting a message here will take you to the publicly available article in order to continue your conversation in public.
 
QuestionGPG Pinmembercspitzer29-Jul-14 10:37 
AnswerRe: GPG PinprofessionalFrank T. Clark29-Jul-14 10:49 
GeneralRe: GPG Pinmembercspitzer29-Jul-14 10:52 
GeneralRe: GPG PinprofessionalFrank T. Clark29-Jul-14 10:54 
QuestionMultiple mapping Pinmemberfeanorgem29-Jul-14 6:43 
AnswerRe: Multiple mapping PinprofessionalFrank T. Clark29-Jul-14 10:43 
GeneralRe: Multiple mapping Pinmemberfeanorgem29-Jul-14 12:55 
GeneralRe: Multiple mapping PinprofessionalFrank T. Clark1-Aug-14 11:07 
GeneralRe: Multiple mapping Pinmemberfeanorgem1-Aug-14 15:49 
QuestionClarifying what you mean... PinmemberMember 873926921-Jul-14 9:17 
AnswerRe: Clarifying what you mean... PinprofessionalFrank T. Clark21-Jul-14 11:33 
GeneralRe: Clarifying what you mean... PinmemberMember 873926927-Jul-14 1:57 
SuggestionRe: Clarifying what you mean... PinprofessionalFrank T. Clark27-Jul-14 2:28 
GeneralRe: Clarifying what you mean... PinprofessionalFrank T. Clark28-Jul-14 4:36 
GeneralRe: Clarifying what you mean... PinmemberMember 87392693-Aug-14 2:02 
GeneralRe: Clarifying what you mean... PinprofessionalFrank T. Clark3-Aug-14 10:54 
GeneralRe: Clarifying what you mean... PinmemberMember 87392694-Aug-14 9:42 
QuestionApparently a file path cannot be relative? PinmemberMember 873926920-Jul-14 2:40 
AnswerRe: Apparently a file path cannot be relative? PinprofessionalFrank T. Clark20-Jul-14 4:26 
AnswerRe: Apparently a file path cannot be relative? PinprofessionalFrank T. Clark20-Jul-14 5:24 
AnswerRe: Apparently a file path cannot be relative? PinprofessionalFrank T. Clark21-Jul-14 8:54 
BugAbout window Pinmembermavru3-Jun-14 0:18 
GeneralRe: About window PinprofessionalFrank T. Clark3-Jun-14 3:09 
QuestionGreat article and very interesting! PinprofessionalVolynsky Alex6-Apr-14 12:51 
AnswerRe: Great article and very interesting! PinprofessionalFrank T. Clark7-Apr-14 2:39 
GeneralRe: Great article and very interesting! PinprofessionalVolynsky Alex7-Apr-14 8:05 
GeneralMy vote of 3 Pinmemberwebmaster4426-Apr-14 9:48 
GeneralRe: My vote of 3 PinprofessionalFrank T. Clark6-Apr-14 9:52 
GeneralRe: My vote of 3 PinmemberDave Cross7-Apr-14 2:15 
QuestionNo other editor with ANSI, UTF8 and Unicode support PinmemberAndreas Falco11-Feb-14 7:32 
AnswerRe: No other editor with ANSI, UTF8 and Unicode support PinprofessionalFrank T. Clark11-Feb-14 7:56 
GeneralRe: No other editor with ANSI, UTF8 and Unicode support PinmemberAndreas Falco11-Feb-14 8:48 
GeneralRe: No other editor with ANSI, UTF8 and Unicode support PinprofessionalFrank T. Clark11-Feb-14 9:45 
AnswerRe: No other editor with ANSI, UTF8 and Unicode support Pinmemberahagel7-Apr-14 8:46 
AnswerRe: No other editor with ANSI, UTF8 and Unicode support PinmemberOscar030-Jul-14 9:17 
QuestionAbsence of printing capability.. Pinmembermungball9911-Dec-13 5:26 
AnswerRe: Absence of printing capability.. [modified] PinprofessionalFrank T. Clark11-Dec-13 11:10 
GeneralRe: Absence of printing capability.. Pinmembermungball9916-Dec-13 8:55 
GeneralRe: Absence of printing capability.. PinprofessionalFrank T. Clark16-Dec-13 10:38 
QuestionI vote you 5 PinmemberWuRunZhe9-Dec-13 14:21 
AnswerRe: I vote you 5 PinprofessionalFrank T. Clark10-Dec-13 1:55 
GeneralMy vote of 5 PinprofessionalPrasad Khandekar23-Sep-13 21:36 
GeneralRe: My vote of 5 PinprofessionalFrank T. Clark24-Sep-13 2:10 
GeneralRe: My vote of 5 Pinmembermatrixcd20-Nov-13 20:41 
GeneralRe: My vote of 5 PinprofessionalFrank T. Clark21-Nov-13 3:27 
BugException when trying to save a file as safe without a key [modified] Pinmember_Nizar23-Sep-13 21:05 
GeneralRe: Exception when trying to save a file as safe without a key [modified] PinprofessionalFrank T. Clark24-Sep-13 2:09 
QuestionEncryption/Decryption Algorithm PinprofessionalMuhammad_Shoaib23-Sep-13 18:56 
AnswerRe: Encryption/Decryption Algorithm PinprofessionalFrank T. Clark24-Sep-13 2:08 
GeneralRe: Encryption/Decryption Algorithm PinmemberRick Bassham7-Oct-13 11:26 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140926.1 | Last Updated 8 Jul 2013
Article Copyright 2013 by Frank T. Clark
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid