VB密码替代算法乱码求教
用VB写了个简单的密码算法,凯撒方法的,代码如下:Dim k As Long
Dim filename As String
Dim tmpb() As Byte
Dim tmpval As Long
Private Sub Command1_Click()
Dim i As Long
'读取密钥
k = IIf(Val(Text3.Text) = 0, 10, Val(Text3.Text) Mod 255)
'逐字节读取文件
Open filename For Binary As #1
i = 0
While Not EOF(1)
ReDim Preserve tmpb(i)
Get #1, i + 1, tmpb(i)
tmpval = i
i = i + 1
Wend
Close #1
'逐字节对文件进行加密
Open filename For Binary As #1
For i = 0 To tmpval - 1
tmpb(i) = (tmpb(i) + k) Mod 255
Put #1, i + 1, tmpb(i)
Next i
Close #1
'在文本框中显示密文
Text2.Text = ""
Open filename For Input As #1
While Not EOF(1)
tmpstr = Input(1, #1)
Text2.Text = Text2.Text + tmpstr
Wend
Close #1
End Sub
Private Sub Command2_Click()
Dim i As Long
Dim tmpstr As String
'读取密钥
k = IIf(Val(Text3.Text) = 0, 10, Val(Text3.Text) Mod 255)
'逐字节读取文件
Open filename For Binary As #1
i = 0
While Not EOF(1)
ReDim Preserve tmpb(i)
Get #1, i + 1, tmpb(i)
tmpval = i
i = i + 1
Wend
Close #1
'逐字节对文件解密
Open filename For Binary As #1
For i = 0 To tmpval - 1
If tmpb(i) < k Then tmpb(i) = 255 - tmpb(i) Else tmpb(i) = tmpb(i) - k
Put #1, i + 1, tmpb(i)
Next i
Close #1
'在文本框中显示明文
Text2.Text = ""
Open filename For Input As #1
While Not EOF(1)
tmpstr = Input(1, #1)
Text2.Text = Text2.Text + tmpstr
Wend
Close #1
End Sub
Private Sub Text1_KeyPress(KeyAscii As Integer)
Dim i As Long
Dim tmpstr As String
If KeyAscii = 13 Then
'读取文件名
filename = Text1.Text
If filename = "" Or Dir(filename) = "" Then
MsgBox "文件不存在!", , "错误"
Text1.Text = ""
filename = ""
Exit Sub
End If
'在文本框中显示文件内容
Text2.Text = ""
Open filename For Input As #1
While Not EOF(1)
tmpstr = Input(1, #1)
Text2.Text = Text2.Text + tmpstr
Wend
Close #1
Command1.Enabled = True
Command2.Enabled = True
End If
End Sub
PS:问题是:例如你明文是:THISISEXAMPLE
但是加密后会有乱码出现,但是解密又能解回来,不知道谁帮我看看下,是不是哪里没弄好,ASII码 255没错吧~~ --------------------编程问答-------------------- 将加密/解密的字符限定在可见字符的范围内,而不是所有的 [0-255] Ascii 码。
比如 ROT13,只是[A-M]与[N-Z]交换、[a-m]与[n-z]交换,其他不变。 --------------------编程问答-------------------- 看不懂啊。 --------------------编程问答-------------------- Google: ROT13 --------------------编程问答--------------------
既然是加密,乱码就乱码呗。
否则就在可打印字符之间替换。
For i = 0 To tmpval - 1
tmpb(i) = (tmpb(i) - 32 + k) Mod 95 + 32
Put #1, i + 1, tmpb(i)
Next i
解密逆运算即可。
补充:VB , API