Â
ÂÂ
Â
Secure Mail
Detailed
Â
Technical
Â
Information
Â
&
Â
In
â
Depth
Â
of
Â
Understanding
Â
of
Â
Application.
SYÂ ChuaÂ
Table
Â
of
Â
Contents
Â
Â
Technical Detail ... 2Â
1 User Account Profile ... 3Â
2. Retrieving & Storing Of Email Messages ... 5Â
2.1  Process of retrieving email messages ... 5Â
2.2  Raw Email Message in itâs Original/ Encryption Stage ... 6Â
2.3  Method of Indexing These Messages (Archive) ... 8Â
2.4  ReâEncryption Of Archives ... 9Â
3. Process of Encrypting Email For Sending A Secured Mail ... 10Â
4. Process of Decrypting Received Secured Mail ... 12Â
5. Shredding of Files ... 17Â
5.1 Source Code ... 17Â
6. Hashing Data/File ... 18Â
6.1 Source Code (Hashing Data & File) ... 18Â
7. Symmetric Encryption ... 19Â
7.1 Source Code (Generating Key/IV) ... 19Â
7.2 Source Code (Encrypting/Decrypting File) ... 20Â
8. Asymmetric Encryption ... 22Â
8.1 Source Code (Generating Keypair & Encrypting Message) ... 22Â
8.2 Source Code (Sign & Verify Digital Signature) ... 23 Â
Â
       ÂTechnical
Â
Detail
Â
Âï· Once Secure Mail started, the application will be created the following in your user directory. o C:\Users\<CurrentUserName>\AppData\Local\SecuredMail [Main Storage] o â¦.\SecuredMail\Config  [For storing SMTP/POP Mail Server information] o â¦.\SecuredMail\Keys  [For storing Public keys]Â
o â¦.\SecuredMail\<uname> [For storing login file for the user account created] o â¦.\....\<uname>\EncryptedMsg [Temporary storage for encrypted attachment to be Â
send]Â
o â¦.\....\<uname>\DecryptedMsg [Temporary storage for decrypted attachment] o â¦.\....\<uname>\<email> [Storing of email achieved ]Â
Note: Except for SMTP/POP Mail Server configuration file and public keys of contacts, all information saved in the remaining folders are encrypted.Â
Â
ï· Symmetric Encryption functions that use to encrypt user profile and file attachments is Rijindael 256 Bits algorithm with the function System.Security.Cryptography.SymmetricAlgorithm.Â
Â
ï· File/Data Hashing functions will also be used to hash File for VirusTotal database checking and also for encrypted file attachment with System.Security.Cryptography. HashAlgorithm Â
ï· Â Asymmetric Encryption is used to encrypt/decrypt key,iv, file hash and digital signature. This encryption is also use to generate the digital signature of the message. Function use is  System.Security.Cryptography.AsymmetricAlgorithm.              Â
1
Â
User
Â
Account
Â
Profile
Â
The user account will be save in a file basing on it login name where a folder will be created basing on it name. Diagram example below refers.Â
 Â
The user file âusr_bob.cfgâ will be saved and encrypted using Rijindael algorithm with the login password generated to be used as Key & IV. Original information found on the config file as below.Â
User Config File (usr_bob.cfg)
Â
[SECUREDMAIL â START] AcctName=Bob  Pass=P@ssw0rd LockApp=True IdleMin=10 Email[email protected] MailServer=Gmail.comÂ
EmailDisplayName=Bob DisplayNameÂ
EmailPass=3m@i1P@ssÂ
ContactEmail[email protected]Â
KeySent=TrueÂ
ContactEmail[email protected]Â
KeySent=FalseÂ
PrivateKey=<RSAKeyValue><Modulus>â¦â¦. </D></RSAKeyValue>Â
PublicKey=<RSAKeyValue><Modulus>â¦â¦</Exponent></RSAKeyValue> [SECUREDMAIL â END]Â
Config Start Person Name PasswordÂ
Screenâlock Enabled? Min idle before activated Email AccountÂ
Mail ServerÂ
Email Display Name Email Password Contactâs email Is you Public Key send? ..Â
..Â
Your RSA Private Key Your RSA Public KeyÂ
Config EndÂ
Â
Once the information is saved or loaded, it will be encrypted and below screenshot is the encrypted content.      Â
2.
Â
Retrieving
Â
&
Â
Storing
Â
Of
Â
Â
Messages
 Â
Â2.1
 Â
Process
Â
of
Â
retrieving
Â
Â
messages
Â
All receiving of email messages from Inbox will be done via POP3 (Post Office Protocol V3). Diagram below showing the process.Â
2.2
 Â
Raw
Â
Â
Message
Â
in
Â
itâs
Â
Original/
Â
Encryption
Â
Stage
 Â
Information received from mail server would be in plain text format as example shown below.Â
Original Message SourceÂ
MIMEâVersion:Â 1.0Â
Received: by 10.50.154.68 with HTTP; Mon, 10 Nov 2014 06:19:09 â0800 (PST)Â
Date: Mon, 10 Nov 2014 22:19:09 +0800Â
DeliveredâTo:Â [email protected]Â
MessageâID:Â <CA+g2nAuYTpf3hbYy5fgWJYBr=7MQj4t=uPZFS7U4dkn8uKv5cg@mail.gmail.com>Â
Subject:Â Â
From: Bob <[email protected]>Â
To: Bob <[email protected]>Â
ContentâType:Â multipart/mixed;Â boundary=f46d0444047895d3e4050781d842Â
Â
ââf46d0444047895d3e4050781d842Â
ContentâType:Â multipart/alternative;Â boundary=f46d0444047895d3df050781d840Â
Â
ââf46d0444047895d3df050781d840Â
ContentâType:Â text/plain;Â charset=UTFâ8Â Â
ââf46d0444047895d3df050781d840Â
ContentâType:Â text/html;Â charset=UTFâ8Â Â
<div dir="ltr"><br></div> Â
ââf46d0444047895d3df050781d840ââÂ
ââf46d0444047895d3e4050781d842Â
ContentâType:Â text/xâpython;Â charset=USâASCII;Â name="test.py"Â
ContentâDisposition:Â attachment;Â filename="test.py"Â
ContentâTransferâEncoding:Â base64Â
XâAttachmentâId: f_i29a0be50  IyEgL3Vzci9iaW4vcHl0aG9uCiMjCiMjIFRoaXMgd2FzIHdyaXR0ZW4gZm9yIGVkdWNhdGlvbmFs IHB1cnBvc2Ugb25seS4gVXNlIGl0IGF0IHlvdXIgb3duIHJpc2suCiMjIEF1dGhvciB3aWxsIGJl IG5vdCByZXNwb25zaWJsZSBmb3IgYW55IGRhbWFnZSEKIyMgV3JpdHRlbiBCeSBTWSBDaHVhLCBz IHByaW50ICdcbiAoXkMpIGludGVycnVwdGVkXG4nCiAgICBleGNlcHQgRU9GRXJyb3I6ICAgICAg ICAgIHByaW50ICdcbiAoXkQpIGludGVycnVwdGVkXG4nCiAgICBleGl0X2dyYWNlZnVsbHkoMCkK CQo= ââf46d0444047895d3e4050781d842ââ Â
Basing on the unique field âMessageâIDâ the data will be hashed with SHA256 and returned with âc937ad223cf274df110ffae2be2bc0efb99e8e97a2bba4f09bc86fb20a6a98daâ. The hashed value willÂ
be search in the email folderÂ
âC:\Users\<Win.Username>\AppData\Local\SecuredMail\Bob\bob@gmail\â to see if the file âc937ad223cf274df110ffae2be2bc0efb99e8e97a2bba4f09bc86fb20a6a98da.encâ exist, if not, it will write the raw message source to the file and encrypted it with user login passwords.Â
 Â
Although as seen on the previous page, the raw message information are in plain text. It will encrypted using Rijindael Algorithm with user login password as Key & IV and look like screenshot shown below. It was only one user click on the message, it will decrypt it to display the information and reâencrypt it.Â
 Â
 Â
2.3
 Â
Method
Â
of
Â
Indexing
Â
These
Â
Messages
Â
(Archive)
Â
Similar technique is also being used to encrypt the Archive index file (Archive.Enc). Below are example of what the original Archive index file will looks like and what it will be shown when encrypted. Information found in the Achieve Index file include:Â
ï· Message Hash IDÂ ï· Message SubjectÂ ï· Message DateÂ ï· Any AttachmentÂ ï· Message SizeÂ
ï· Message Status From ServerÂ ï· Message Read StatusÂ
Â
Achieve Index File (Original clear text) Â
<MsgIDHash>CE3D53ABBA720AFA0600C0DE88997BED99F7A3829FEB1CE2A275A552CAB86D10< /MsgIDHash><MsgSubject>SECUREDâMAIL : My Secured Mail SubjectÂ
Title</MsgSubject><MsgFrom>"Gmail Person Two"Â
<[email protected]></MsgFrom><MsgDate>Sat, 03 Jan 2015 04:58:09 â0800Â
(PST)</MsgDate><MsgAttach>1</MsgAttach><MsgSize>101560</MsgSize><MsgStatus>+OK</M sgStatus><MsgRead>Yes</MsgRead>Â
Â
<MsgIDHash>8EA6D9585D9F1934A4F7A018F652D9EE5487562D99CA13089E9351A54ECA9227</ MsgIDHash><MsgSubject>My Secured Mail Subject Title</MsgSubject><MsgFrom>"Gmail Person Two" <[email protected]></MsgFrom><MsgDate>Sat, 03 Jan 2015 04:45:13 â0800 (PST)</MsgDate><MsgAttach>1</MsgAttach><MsgSize>101539</MsgSize><MsgStatus>+OK</Ms gStatus><MsgRead>Yes</MsgRead>Â
Â
2.4
 Â
Re
â
Encryption
Â
Of
Â
Archives
Â
As mentioned that the email messages and archive index files were all encrypted using user login passwords, once the user password is changed, application will reâencrypt these files with the new login password in order to make these files still readable after password changes. Â
                        Â
3.
Â
Process
Â
of
Â
Encrypting
Â
Â
For
Â
Sending
Â
A
Â
Secured
Â
Â
Below is diagram of the process from drafting of email & attachment of files to encrypting it into a container for sending to the recipient.  Process are divided into Â
ï· Yellow Colour (1â3)  ~ Email ContentÂ Â ï· Blue Colour (1â2) ~ File AttachmentÂ ï· Green Colour (1â2) ~ Randomize Key & IVÂ
ï· Red Colour (1â2) ~ Encryption before email sending Â
 Â
 Â
 Yellow Colour (Email Content Processing)Â
1) The email subject and message content are divided into 2 filesÂ ï· EmailSubject.txt stores the email SubjectÂ
ï· EmailContent.txt stores the email contentÂ
2) Message content of EmailContent.txt will be hashed using SHA1 and using the senderâs RSA private key, it will be signed to create a digital signature of the content. The digital signature will be in Base64 format which will subsequently inserted into Hash.txt (Redâ1)Â
3) Both âEmailSubject.txtâ & âEmailContent.txtâ will be compressed into Attachment.zip and subsequently encrypted to âAttachment.encâ (Greenâ2)Â
Blue Colour (File Attachment Process)Â
1) The selected files will be hashed using SHA256 algorithm and check against the VirusTotal Database and revert with detection result.Â
2) The selected files will compressed and added together with âEmailSubject.txtâ & âEmailContent.txtâ which will subsequently encrypted to âAttachment.encâ (Greenâ2)Â
Green Colour (Randomize Key & IV)Â
1) Rijindael algorithm will be used for generating randomize Key & IV for Symmetric encryption. The Key & IV will be converted into Base64 format which will be inserted into âHash.txtâ (Redâ 1)Â
2) These Key & IV will be used to encrypt the compressed file âAttachment.zipâ into âAttachment.EncâÂ
3) The encrypted âAttachment.Encâ will be hashed using SHA512 and the hashed value will be stored in âHash.txtâ (Redâ1)Â
Red Colour (Final Encryption before sending)Â
1) The file âHash.txtâ which storedÂ
a. Digital Signature of message contentÂ
b. Encryption/Decryption Key & IV for âAttachment.EncâÂ
c. SHA512 Hashed value of âAttachment.Encâ (For file integrity check)Â
âHash.txtâ will be using Asymmetric Encryption method to encrypt (i.e using recipientâs RSA Public Key to encrypt) and saved as âHash.encâÂ
2) Both âAttachment.Encâ (Encrypted using Symmetric) and âHash.encâ (Encrypted using Asymmetric) will be compressed into âEncryptedData.zipâ and then send to recipient. Â
Note: All these files that were processed are stored in Â
âC:\Users\<Win.Username>\AppData\Local\SecuredMail\Bob\EncryptedMsgâ folder which will be removed after the secured mail is sent.Â
  Â
4.
Â
Process
Â
of
Â
Decrypting
Â
Received
Â
Secured
Â
Â
Decryption process are quite similar to the process of encryption but in reverse order and having integrity checks performed. Below is diagram of the process of decryption.  Process are divided into Â
ï· Red Colour (1â2) ~ Decryption of encrypted filesÂ
ï· Blue Colour (1â3) ~ Extraction of key information & integrity checksÂ ï· Yellow Colour (1â3)  ~ Extraction of attachment files & email content       Â
Red Colour (Decryption of Encrypted Files)Â
Prior to the decryption, the attachment âEncryptedData.Zipâ will be downloaded from the email message and extracted the 2 files (Hash.Enc & Attachment.Enc) to the directory C:\Users\<Win.Username>\AppData\Local\SecuredMail\Bob\DecryptedMsgâÂ
1) âHash.Encâ will be decrypted with Asymmetric decryption using the recipientâs Private Key and saved as âHash.txtâ. The file contains the digital signature of the message content, decryption key & IV which is in Base64 format for âAttachment.encâ and also the SHA512 hash value of âAttachment.encâÂ
2) âAttachment.Encâ will be decrypted with Symmetric decryption using the Key & IV found in âHash.txtâ and saved as âAttachment.zipâÂ
Blue Colour (Extraction of key information & integrity checks)Â
1) âHash.txtâ was decrypted from âHash.Encâ using the recipientâs Private Key. It contain digital signature of the message content, decryption key & IV and file hash value for âAttachment.encâ.Â
2) The SHA512 Hash value found in âHash.txtâ will be check against the downloaded âAttachment.encâ for file integrity checks. Â
3) The Digital Signature which is found in âHash.txtâ will be decrypted using senderâs public key and verify with the SHA1 hash value of the extracted content found in âEmailContent.txtâ Â
 Yellow Colour (Email Content Processing)Â
1)  âAttachment.zipâ contains âEmailContent.txtâ, âEmailSubject.txtâ and other attached files will be extracted to Â
 C:\Users\<Win.Username>\AppData\Local\SecuredMail\Bob\DecryptedMsgâ 2) The message content found in âEmailContent.txtâ will be extracted and display together withÂ
the Subject and attached files to userâs screen.Â
3) The message content will also hashed with SHA1 algorithm and thereafter compare the value with the decrypted digital signature found in âHash.txtâ.Â
        Â
Below screenshots of the main attachment âEncrytedData.Zipâ, the encrypted âAttachment.Encâ, the content of âHash.Encâ and also the screenshot on how the Secure Mail looks like using webâbased.Â
Screenshot of âEncryptedData.Zipâ Â
Â
 Screenshot of encrypted âAttachment.Encâ in BinaryÂ
 Screenshot of encrypted âHash.Encâ in Base64 FormatÂ
  Â
 Screenshot of the Secure Mail looks like in web browser.Â
                Â
5.
Â
Shredding
Â
of
Â
Files
Â
Instead of deleting file through the function âSystem.IO.File.Delete( FileToDelete )â which can be easily recovered using Undelete software available in the market, SecuredMail use the method of overwriting the existing file with null 5 times before deleting it. Â
Although there may be some advanced ways of recovering original data that were overwritten on a harddisk as presented on a paper by computer scientist, Peter Gutmann by recovering these data through the use of magnetic force microscope (MFM), SecuredMail had done the minimal of securing overwriting the existing data with null before deleting It as although Gutmann's theory may be correct, there is no practical evidence that overwritten data can be recovered, while research has shown to support that overwritten data cannot be recovered.
5.1
Â
Source
Â
Code
Â
Public Function DeleteFile(strFileName As String) As Boolean         Dim ByteArray() As ByteÂ
        If File.Exists(strFileName) = True Then       Dim infoReader As System.IO.FileInfoÂ
      infoReader = My.Computer.FileSystem.GetFileInfo(strFileName)       Dim writebye(infoReader.Length) As ByteÂ
      Dim writesize As Long = (infoReader.Length * 2) + 3       ReDim ByteArray(CInt(writesize))Â
      For I As Long = 0 To (writesize)       ByteArray(CInt(I)) = &H0       NextÂ
      TryÂ
      For i = 0 To 5Â
      Dim sw As New StreamWriter(strFileName)       sw.Write(UnicodeBytesToString(ByteArray))       sw.Flush():sw.Close()Â
      For l As Long = 0 To (writesize)       ByteArray(CInt(l)) = &H0 + 1       Next       Next       Catch ex As Exception       End Try       Try       File.Delete(strFileName)       Catch ex As Exception       End Try       Return True         Else       Return False         End If     End Function References : Â
ï· [Secure Deletion of Data from Magnetic and SolidâState Memory] https://www.cs.auckland.ac.nz/~pgut001/pubs/secure_del.htmlÂ ï· [Overwriting Hard Drive Data: The Great Wiping Controversy]Â
http://www.vidarholen.net/~vidar/overwriting_hard_drive_data.pdfÂ ï· [Overwriting Hard Drive Data]Â
6.
Â
Hashing
Â
Data/File
Â
Hash mainly using in the application are SHA512 and SHA256 in the case for hashing file as to check on VirusTotal Database. Â
6.1
Â
Source
Â
Code
Â
(Hashing
Â
Data
Â
&
Â
File)
Â
Public Enum HashingUseÂ'Define the enumeration for AlgorithmUse.Â
MD5 = 0         RIPEMD160 = 1         SHA1 = 2         SHA256 = 3         SHA384 = 4         SHA512 = 5 End EnumÂ
Public Function HashData(ByVal strData As String, ByVal UseHash As HashingUse, _Â
Optional Spaces As Boolean = False) As String         Dim HashIndex As Integer = UseHashÂ
        Dim ha As HashAlgorithm = HashAlgorithm.Create(HashUse(HashIndex))         Dim hashValue() As ByteÂ
        hashValue = ha.ComputeHash(UnicodeStringToBytes(strData))         Dim info As Byte() = NewÂ
UTF8Encoding(True).GetBytes(PrintByteArray(hashValue))         HashData = PrintByteArray(hashValue)Â
        If Spaces = True ThenÂ
      HashData = AddSpaceToString(HashData, 2)         End If         Return HashData End Function  Â
Public Function HashFile(ByVal sfile As String, ByVal UseHash As HashingUse, _Â
Optional Spaces As Boolean = False) As StringÂ
TryÂ
If File.Exists(sfile) = False ThenÂ
MsgBox("File [" & sfile & "] not found!", vbInformation, _Â
"File Not Found")       Return ""Â
End IfÂ
       Dim HashIndex As Integer = UseHashÂ
       Dim ha As HashAlgorithm = HashAlgorithm.Create(HashUse(HashIndex))        Dim hashValue() As ByteÂ
       Dim fileStream As FileStream = File.Open(sfile, FileMode.Open)        fileStream.Position = 0Â
       hashValue = ha.ComputeHash(fileStream)Â
       Dim info As Byte() = New UTF8Encoding(True).GetBytes(PrintByteArray(hashValue))        fileStream.Close()Â
       HashFile = PrintByteArray(hashValue)        If Spaces = True ThenÂ
        HashFile = AddSpaceToString(HashFile, 2)Â
End IfÂ
       Return HashFileÂ
Catch ex As ExceptionÂ
MsgBox("Error in hashing [" & sfile & "].", vbInformation, "Hashing Error")Â
Return ""Â
End TryÂ
7.
Â
Symmetric
Â
Encryption
Â
Although the Encryptionâs algorithm that is use in the application are mainly âRijindaelâ, we coded it to be able to use other algorithm to allow us to easily change or add in other algorithm if required. Below are the source codes for generating symmetric Key/IV and encrypting/decrypting files.Â
7.1
Â
Source
Â
Code
Â
(Generating
Â
Key/IV)
Â
Â
Dim AlgoUse() As String = {"Rijndael", "AES", "TripleDES", "RC2", "DES"}Â
Dim AlgoKeySize() As String = {"256", "256", "192", "128", "64"}Â
Dim AlgoBlockSize() As String = {"256", "128", "64", "64", "64"}Â
Â
Public Function GenerateKeyOrIV(ByVal UseAlgorithm As AlgorithmUse, _Â
ByVal ActionKeyOrIV As KeyOrIV, _Â
Optional ByVal strPassword As String = "", _Â
Optional ByVal Rotation As Integer = 0) As Byte() Â
GenerateKeyOrIVÂ =Â UnicodeStringToBytes("")Â
TryÂ
'Setting of Algorithm and BlocksizeÂ
Dim AlgoIndex As Integer = UseAlgorithmÂ
       Dim sa As SymmetricAlgorithm = SymmetricAlgorithm.Create(AlgoUse(AlgoIndex))        sa.BlockSize = AlgoBlockSize(AlgoIndex)Â
       sa.KeySize = AlgoKeySize(AlgoIndex)Â
'Process to Randomize Key/IV basing on user selectionÂ
If strPassword = "" ThenÂ
        If ActionKeyOrIV = KeyOrIV.KeyGenerate Then       sa.GenerateKey()Â
      Return sa.KeyÂ
End IfÂ
      If ActionKeyOrIV = KeyOrIV.IVGenerate Then        sa.GenerateIV()Â
       Return sa.IVÂ
End IfÂ
ElseÂ
'Process of using Password to generate Key/IV instead of RandomizeÂ
Dim chrData() As Char = strPassword.ToCharArray      Â
Dim intLength As Integer = chrData.GetUpperBound(0)            Dim bytDataToHash(intLength) As ByteÂ
For i As Integer = 0 To chrData.GetUpperBound(0)       bytDataToHash(i) = CByte(Asc(chrData(i)))Â
NextÂ
'Key/IV will generate base on SHA512 hash of the passwordÂ
Dim SHA512 As New System.Security.Cryptography.SHA512Managed        Â
Dim bytResult As Byte()       bytResult = bytDataToHashÂ
      For i = 0 To Rotation       '        bytResult = SHA512.ComputeHash(bytResult)Â
NextÂ
Dim AKS As Integer       Dim ABS As IntegerÂ
'Basing on userâs selection (Key or IV) then return result       If ActionKeyOrIV = KeyOrIV.KeyGenerate ThenÂ
       AKS = Int(AlgoKeySize(AlgoIndex) / 8) â 1Â
       Dim byteIV(ABS) As ByteÂ
       For i As Integer = 32 To 32 + ABS       byteIV(i â 32) = bytResult(i)        NextÂ
       Return byteIV       End IfÂ
      End IfsÂ
'Display error message if found.Â
Catch ex As ExceptionÂ
MsgBox("Error generating Key/IV !", vbExclamation, "Key/IV Generation Error")Â
End TryÂ
Return GenerateKeyOrIVÂ
End FunctionÂ
7.2
Â
Source
Â
Code
Â
(Encrypting/Decrypting
Â
File)
Â
Â
Public Function EncryptDecryptFile(ByVal UseAlgorithm As AlgorithmUse, _Â
Direction As CryptoAction, srcFile As String, DstFile As String, _Â
ReplaceWithoutPrompt As Boolean, byteKey() As Byte, byteIV() As Byte, _Â
pbStatus As ToolStripProgressBar, Optional DontPrompt As Boolean = False) AsÂ
Boolean Â
' Check Existance for file before processingÂ
If DontPrompt = False ThenÂ
If File.Exists(srcFile) = False ThenÂ
        MsgBox("The specified source file [" & srcFile & "] is not found !" & _Â
vbCr & "Process aborted.", vbExclamation, "File Not Found")Â
Return FalseÂ
End IfÂ
       If ReplaceWithoutPrompt = False Then         If File.Exists(DstFile) = True ThenÂ
      Dim Qus As Integer = MsgBox("The specified destination file [" &Â
_Â
DstFile & "] is exist!" & vbCr & vbCr & _Â
"Do you want to replace ?.", vbQuestion + vbYesNo + _Â
 vbDefaultButton2, "Replace File ?")Â
If Qus = vbYes ThenÂ
        DeleteFile(DstFile)Â
ElseÂ
        MsgBox("Process Aborted by user", vbInformation,Â
"Aborted")        Return False End If End If End If End If Try Â
'Set Read & Write file for SrcFile & DstFileÂ
fsInput = New System.IO.FileStream(srcFile, FileMode.Open, FileAccess.Read)        fsOutput = New System.IO.FileStream(DstFile, FileMode.OpenOrCreate, _     _FileAccess.Write)Â
'Setup algorithm basing on user selectionÂ
Dim AlgoIndex As Integer = UseAlgorithmÂ
       Dim sa As SymmetricAlgorithm = SymmetricAlgorithm.Create(AlgoUse(AlgoIndex))        TryÂ
' Setting up the block and key size basing on the algorithm       sa.BlockSize = AlgoBlockSize(AlgoIndex)Â
      sa.KeySize = AlgoKeySize(AlgoIndex)Â
Catch ex As ExceptionÂ
        MsgBox("There could be some problem with the Block/Key size !", _Â
Return FalseÂ
End TryÂ
'Declare variables for encrypt/decrypt process.Â
       Dim bytBuffer(4096) As Byte 'holds a block of bytes for processing        Dim lngBytesProcessed As Long = 0 'running count of bytes processed        Dim lngFileLength As Long = fsInput.Length 'the input file's length        Dim intBytesInCurrentBlock As Integer 'current bytes being processed        Dim csCryptoStream As CryptoStreamÂ
'Determine if encryption or decryption and setup CryptoStream.Â
Select Case DirectionÂ
        Case CryptoAction.ActionEncryptÂ
       csCryptoStream = New CryptoStream(fsOutput, _Â
   sa.CreateEncryptor(byteKey, byteIV), CryptoStreamMode.Write)Â
Case CryptoAction.ActionDecryptÂ
      csCryptoStream = New CryptoStream(fsOutput, _Â
sa.CreateDecryptor(byteKey, byteIV), CryptoStreamMode.Write)Â
End SelectÂ
       'Loop until encryption/decryption until source file read the endÂ
       While lngBytesProcessed < lngFileLengthÂ
      intBytesInCurrentBlock = fsInput.Read(bytBuffer, 0, 4096)       csCryptoStream.Write(bytBuffer, 0, intBytesInCurrentBlock)Â
      lngBytesProcessed = lngBytesProcessed + CLng(intBytesInCurrentBlock)Â
End WhileÂ
'Close FileStreams and CryptoStream.        csCryptoStream.Close()Â
       fsInput.Close()        fsOutput.Close()        Return TrueÂ
'Catch file not found error.Â
Catch When Err.Number = 53 'if file not foundÂ
If DontPrompt = False Then MsgBox("The specified file is not found !",_Â
vbExclamation, "File Not Found")       DeleteFile(DstFile)Â
      'Catch all other errors. And delete partial files.Â
CatchÂ
fsInput.Close()Â Â Â Â Â Â Â Â fsOutput.Close()Â
       If Direction = CryptoAction.ActionDecrypt Then         DeleteFile(DstFile)Â
      If DontPrompt = False Then MsgBox("Invalid Password Entered !!",_  vbExclamation, "Invalid Password")Â
ElseÂ
       If DontPrompt = False Then MsgBox("Error: This file cannot be _Â
    encrypted !", vbExclamation, "Invalid File")Â
End If End Try Return False End Function         Â
8.
Â
Asymmetric
Â
Encryption
Â
The asymmetric encryption use in the application are for encrypting/decrypting key, IV, hashes and digital signature for the secure mail. Â
 Â
8.1
Â
Source
Â
Code
Â
(Generating
Â
Keypair
Â
&
Â
Encrypting
Â
Message)
Â
Â
'Generating new keypair using RSACryptoServiceProviderÂ
Public Shared Function CreateNewKeys() As KeypairÂ
TryÂ
        Using RSA As New RSACryptoServiceProvider       RSA.KeySize = 2048Â
      Dim Keys As New KeypairÂ
  'Output Private & Public will be in XML Format       Keys.Privatekey = RSA.ToXmlString(True)       Keys.Publickey = RSA.ToXmlString(False)       Return KeysÂ
       End Using         Catch ex As ExceptionÂ
      Throw New Exception("Keypair.CreateNewKeys():" & ex.Message, ex)Â
End TryÂ
End FunctionÂ
Â
'Encrypting Message (Sub class will be called)Â
Private Function EncryptMessage(sDataToEncrypt As String, sPublicKey As String) AsÂ
StringÂ
    Dim CombineTxt As String = ""Â
    TryÂ
Dim ln As Integer = Len(sDataToEncrypt)        Dim md As Integer = ln / 50Â
       Dim rmd As Integer = ln Mod 50        Dim a As Integer = 1Â
       For i = 0 To mdÂ
       Dim EncryptedMessage As SecuredMail.RSAResult = SecuredMail.RSA.Encrypt _        (Mid(sDataToEncrypt, a, 50), sPublicKey)Â
       CombineTxt += EncryptedMessage.AsBase64String & vbLf        a = a + 50Â
       NextÂ
       If rmd > 0 ThenÂ
       Dim EncryptedMessage As SecuredMail.RSAResult = SecuredMail.RSA.Encrypt _        (Mid(sDataToEncrypt, a, rmd), sPublicKey)Â
       CombineTxt += EncryptedMessage.AsBase64String & vbLfÂ
       End IfÂ
       DisplayStatus("Encrypted..")    Catch ex As ExceptionÂ
       MsgBox(Err.Description)Â
       DisplayStatus("RSA Encryption Error : " + ex.Message)Â
   End Try    Return CombineTxt End Function      Â
8.2
Â
Source
Â
Code
Â
(Sign
Â
&
Â
Verify
Â
Digital
Â
Signature)
Â
Â
Private Function HashAndSignData(ByVal sData As String, PrivateKey As String) AsÂ
StringÂ
    Dim rsaPrivateParams As RSAParameters     Dim RSA As New RSACryptoServiceProvider     TryÂ
        RSA.FromXmlString(PrivateKey)Â
        rsaPrivateParams = RSA.ExportParameters(True)         Dim Hash As New SHA1ManagedÂ
        'import private key params into instance of RSACryptoServiceProvider         RSA.ImportParameters(rsaPrivateParams)Â
        'compute hash with algorithm specified as here we have SHA!Â
        Dim HashedData() As Byte = Hash.ComputeHash(UnicodeStringToBytes(sData))         Dim HashedDataHex As String = Bytes_To_String2(HashedData)Â
        ' Sign Data using private key & OID is simple name of the algorithm for which       to get the object identifier (OID)Â
        Return HashedDataHex & vbLf & ByteToBase64(RSA.SignHash(HashedData, _       CryptoConfig.MapNameToOID("SHA1")))     Catch ex As Exception         Return ""     End Try     Return "" End Function Â
Private Function VerifySignature(ByVal sData As String, ByVal Base64Signature AsÂ
String,_Â
      PublicKey As String) As StringÂ
    Dim RSA As New RSACryptoServiceProvider     Dim rsaPubParams As RSAParametersÂ
    Dim DigitalSignature As Byte() = Base64ToByte(Base64Signature)     TryÂ
        RSA.FromXmlString(PublicKey)Â
        rsaPubParams = RSA.ExportParameters(False)Â
        'create new instance of SHA1 hash algorithm to compute hash         Dim Hash As New SHA1ManagedÂ
        'a byte array to store hash value         Dim HashedData() As ByteÂ
        'import  public key params into instance of RSACryptoServiceProvider         RSA.ImportParameters(rsaPubParams)Â
        'compute hash with algorithm specified as here we have SHA1         HashedData = Hash.ComputeHash(UnicodeStringToBytes(sData))         Dim HashedDataHex As String = Bytes_To_String2(HashedData)Â
        ' Sign Data using public key and OID is simple name of the algorithm for whichÂ
_Â
      to get the object identifier (OID)Â
        Dim PassOrFail As Boolean = RSA.VerifyHash(HashedData, _        CryptoConfig.MapNameToOID("SHA1"), DigitalSignature)Â
        Dim ValidOrNot As String = ""         If PassOrFail = True ThenÂ
      ValidOrNot = "Digital Signature Is Valid"Â
        ElseÂ
      ValidOrNot = "Digital Signature Is Invalid"         End IfÂ
        Return HashedDataHex & vbLf & ValidOrNot     Catch ex As ExceptionÂ