使用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