使用VB.NET加密文件
2024-07-10 13:01:30
供稿:網友
本文介紹使用xor加密算法對數據進行加密, 這是一種很簡單的算法,使用了盡量簡單的vb編程方法,通俗易懂。我們可以采用更安全的算法如des算法,idea算法等。各位如有任何見解,請不吝賜教。
在窗體中添加一richtextbox,設置其name屬性為sourcefile,multiline屬性為true,scrollbars屬性為3-both。添加一mainmenu,設置一菜單項“文件”,其下有“打開”,“保存”,“加密”,“解密”,“算子”等子菜單項。
以下是大致的程序界面:
public class form1
inherits system.windows.forms.form
dim strnum as string
private sub form1_load(byval eventsender as system.object, byval eventargs as system.eventargs) handles mybase.load
strnum = "password"
end sub
private sub form1_resize(byval eventsender as system.object, byval eventargs as system.eventargs) handles mybase.resize
sourcefile.width = form1.definstance.width
sourcefile.height = form1.definstance.height
end sub
'解密過程,對xor算法而言,解密和加密過程是完全一樣的
private function xorout(byref strnum as string, byref strtext as string) as string
dim i as integer
dim xorvalue1 as short
dim xorvalue2 as short
dim strresult as string
for i = 1 to len(strtext)
xorvalue1 = asc(mid(strtext, i, 1))
xorvalue2 = asc(mid(strnum, (i mod len(strnum)) + 1, 1))
strresult = strresult & chr(xorvalue1 xor xorvalue2)
next
xorout = strresult
end function
private sub menudeencrypt_click(byval sender as system.object, byval e as system.eventargs) handles menudeencrypt.click
sourcefile.text = xorout(strnum, (sourcefile.text))
end sub
private sub menuencrypt_click(byval sender as system.object, byval e as system.eventargs) handles menuencrypt.click
sourcefile.text = xorout(strnum, (sourcefile.text))
end sub
private sub menuopen_click(byval sender as system.object, byval e as system.eventargs) handles menuopen.click
dim openfile1 as new openfiledialog
' determine whether the user selected a file from the openfiledialog.
if (openfile1.showdialog() = dialogresult.ok) _
and (openfile1.filename.length > 0) then
' load the contents of the file into the richtextbox.
sourcefile.loadfile(openfile1.filename, _
richtextboxstreamtype.plaintext)
end if
end sub
private sub menusave_click(byval sender as system.object, byval e as system.eventargs) handles menusave.click
' create a savefiledialog to request a path and file name to save to.
dim savefile1 as new savefiledialog
' initialize the savefiledialog to specify the rtf extension for the file.
'savefile1.defaultext = "*.rtf"
'savefile1.filter = "rtf files|*.rtf"
' determine if the user selected a file name from the savefiledialog.
if (savefile1.showdialog() = dialogresult.ok) _
and (savefile1.filename.length) > 0 then
' save the contents of the richtextbox into the file.
sourcefile.savefile(savefile1.filename, _
richtextboxstreamtype.plaintext)
end if
end sub
private sub menunum_click(byval sender as system.object, byval e as system.eventargs) handles menunum.click
strnum = inputbox("請輸入加密算子", "設置加密算子")
end sub
end class