Secure Mail Detailed Technical Information & In Depth of Understanding of Application. SY Chua SYWORKS PROGRAMMING
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 1 P age
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. 2 P age
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=bob.email1@gmail.com MailServer=Gmail.com EmailDisplayName=Bob DisplayName EmailPass=3m@i1P@ss ContactEmail=alice@gmail.com KeySent=True ContactEmail=alice@outlook.com 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 3 P age
Once the information is saved or loaded, it will be encrypted and below screenshot is the encrypted content. 4 P age
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. 5 P age
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: bob@gmail.com Message ID: <CA+g2nAuYTpf3hbYy5fgWJYBr=7MQj4t=uPZFS7U4dkn8uKv5cg@mail.gmail.com> Subject: From: Bob <bob@gmail.com> To: Bob <bob@gmail.com> 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. 6 P age
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. 7 P age
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" <sy.persontwo@gmail.com></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" <sy.persontwo@gmail.com></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> Screenshot of encrypted Archive.enc 8 P age
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. 9 P age
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 10 P age
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. 11 P age
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 12 P age
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. 13 P age
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 14 P age
Screenshot of encrypted Hash.Enc in Base64 Format 15 P age
Screenshot of the Secure Mail looks like in web browser. 16 P age
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 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] http://digital forensics.sans.org/blog/2009/01/15/overwriting hard drive data/ 17 P age
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) 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 "" 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) Return HashFile Catch ex As Exception MsgBox("Error in hashing [" & sfile & "].", vbinformation, "Hashing Error") Return "" End Try End Function 18 P age
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 If ActionKeyOrIV = KeyOrIV.IVGenerate Then sa.generateiv() Return sa.iv 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 bytekey(aks) As Byte For i As Integer = 0 To AKS bytekey(i) = bytresult(i) Next Return bytekey Else ABS = Int(AlgoBlockSize(AlgoIndex) / 8) 1 19 P age
Dim byteiv(abs) As Byte For i As Integer = 32 To 32 + ABS byteiv(i 32) = bytresult(i) Next Return byteiv s '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 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 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!", _ vbcritical, "Encryption/Decryption Error") 20 P age
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 Try Return False End Function 21 P age
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 DisplayStatus("Encrypted..") Catch ex As Exception MsgBox(Err.Description) DisplayStatus("RSA Encryption Error : " + ex.message) End Try Return CombineTxt End Function 22 P age
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" Return HashedDataHex & vblf & ValidOrNot Catch ex As Exception Return "" & vblf & "Error: Unable To Verify Digital Signature" End Try Return "" & vblf & "Error: Unable To Verify Digital Signature" End Function 23 P age