Highlights
All Snippets
Top 100 Snippets
Librarians
gbCodeLib

By Language
VB6
JavaScript
Perl
HTML
SQL
Java
DOS

GBIC >> Source Code >> Visual Basic >> Snippet

Encrypt a file (uses password)


Function EncryptFile(FileName As String , Key As String ) As Boolean

'validate the file name
If Dir(FileName) = "" Then
   EncryptFile = False
    Exit Function
End If

'read the file into a Byte array  B()
Open FileName For Binary As #1
    Redim B(LOF(1) - 1) As Byte
    Get #1, , B
Close #1

'encrypt the array
Dim i As Long , K As String
For i = 0 To Ubound (B)
 K = Mid (Key, i Mod Len(Key) + 1, 1) 'next character from Key
  'next encrypted character - convert to ASCII, XOR them, and convert to a character again
 B(i) = B(i) Xor Asc (K)
Next i

'write the file
Open FileName For Binary As #1
   Put #1, , B
Close #1

EncryptFile = True

End Function