• No results found

Secure Mail. Detailed Technical Information & In Depth of Understanding of Application. SY Chua SYWORKS PROGRAMMING

N/A
N/A
Protected

Academic year: 2021

Share "Secure Mail. Detailed Technical Information & In Depth of Understanding of Application. SY Chua SYWORKS PROGRAMMING"

Copied!
24
0
0

Loading.... (view fulltext now)

Full text

(1)

 

 

 

 

Secure Mail

Detailed

 

Technical

 

Information

 

&

 

In

‐

Depth

 

of

 

Understanding

 

of

 

Application.

SY Chua 

(2)

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   

 

               
(3)

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.                             

(4)

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 

 

(5)

Once the information is saved or loaded, it will be encrypted and below screenshot is the encrypted  content.             

(6)

2.

 

Retrieving

 

&

 

Storing

 

Of

 

Email

 

Messages

  

 

2.1

  

Process

 

of

 

retrieving

 

email

 

messages

 

All receiving of email messages from Inbox will be done via POP3 (Post Office Protocol V3). Diagram  below showing the process. 

(7)

2.2

  

Raw

 

Email

 

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. 

   

(8)

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. 

   

   

(9)

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> 

 

(10)

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.  

                                                 

(11)

3.

 

Process

 

of

 

Encrypting

 

Email

 

For

 

Sending

 

A

 

Secured

 

Mail

 

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   

   

   

(12)

 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. 

     

(13)

4.

 

Process

 

of

 

Decrypting

 

Received

 

Secured

 

Mail

 

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               

(14)

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”. 

                 

(15)

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 

(16)

  Screenshot of encrypted “Hash.Enc” in Base64 Format 

     

(17)

  Screenshot of the Secure Mail looks like in web browser. 

                                 

(18)

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] 

(19)

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 

(20)

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 

(21)

       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 !", _ 

(22)

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                   

(23)

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             

(24)

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 

References

Related documents