我正在制作一个自定义加密应用程序并且我在更换部分停留。
例如,我有字符串"AB12AB12"
,我想加密它,以便每个A变为1,每个B a 2,每1个A和每2个B.如果一切正常,输出应该是12AB12AB但是这就是:
Private Sub Encrypt()
Dim str As String = "AB12AB12"
str = str.Replace("A", "1") 'now the output is "1B121B12"'
str = str.Replace("B", "2") 'now the output is "12121212"'
str = str.Replace("1", "A") 'this is where it goes wrong, output is now "A2A2A2A2"
str = str.Replace("2", "B") 'now the output is "ABABABAB" and it should be "12AB12AB"
output = str
End Sub
问题是,使用此代码,您将继续更换所有内容,包括之前的替换。也许有一个选项可以同时替换每个角色,这样替换就不会被替换......
答案 0 :(得分:2)
当您使用Replace
进行替换时,您会得到一个包含已处理和未处理的混合字符的字符串,并且您无法区分它们。改为从头到尾处理字符串:
Private Function Encrypt(str as string) as String
Dim source As String = "AB12"
dim dest as string = "12AB"
Dim result As New StringBuilder(str.Length)
For Each c As Char In str
result.Append(dest(source.IndexOf(c)))
Next
return result.ToString()
End Function
注意:我为该方法留下了名称Encrypt
,尽管替换密码现在通常不被认为是加密。
答案 1 :(得分:0)
这种失败的原因是因为如果你用"A" -> "1"
修改str,那么转换回时也会使用这些'1'
个字符:
"AB12AB12" --a>1--> "1B121B12"
"1B121B12" --b>2--> "12121212"
"12121212" --1>a--> "A2A2A2A2"
"A2A2A2A2" --2>b--> "ABABABAB"
基本上有两种方法可以做到这一点:
<强>字符每字符强>
在这里,您每次迭代获取一个字符并将其转换为相应的值:
Private Sub Encrypt()
Dim str As String = "AB12AB12"
Dim fmc As Char() = {"A","B","1","2"}
Dim toc As Char() = {"1","2","A","B"}
Dim sb As New StringBuilder(str.Length)
Dim i As Integer
For i As Integer = 1 To str.Length-1
sb.Append(fmc(Array.IndexOf(toc,GetChar(str,i))))
Next
output = sb.ToString()
End Sub
临时角色
如果你不知道'3'
(或者会出现另一个角色,你可以简单说明):
Private Sub Encrypt()
Dim str As String = "AB12AB12"
str = str.Replace("A", "3")
str = str.Replace("1", "A")
str = str.Replace("3", "1")
str = str.Replace("B", "3")
str = str.Replace("2", "B")
str = str.Replace("3", "B")
output = str
End Sub
然而,这会降低性能。
在旁注中,正如@HansPassant已经指出的那样,你最好不要设计自己的加密系统。例如,这可以通过频率分析轻松解决。
答案 2 :(得分:0)
这里我提出了一种与你讨论不同的方法,检查可能性
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
MsgBox(encrypt(plain_text.Text, replace_it.Text, replace_with.Text))
'display the result in the message box
End Sub
以下是用于执行加密的函数:
Public Function encrypt(ByVal str As String, ByVal frm As String, ByVal replace As String) As String
Dim cipher As String
cipher = ""
For i As Integer = 0 To Len(str) - 1 'check each character separately
If getbyte(str, i) = frm Then
cipher = cipher & replace 'replace the character if is same as the requested
Else
cipher = cipher & getbyte(str, i)
End If
Next
Return cipher.ToString
End Function
函数获取字符串中的每个字符
Private Function getbyte(ByVal s As String, ByVal place As Integer) As String
If place < Len(s) Then
place = place + 1
getbyte = Mid(s, place, 1)
Else
getbyte = ""
End If
End Function