您的位置:首页 > 编程语言 > VB

【VB.Net】使用SHA256进行简单的XOR文本加密与解密

2016-02-14 22:43 1491 查看
以下代码已经编译成库,可直接引用调用,也可自行编译。语法简单,应该不会有太多的问题。也可自行对最终的编码进行旋转、对调等。

从Runplus.Studio下载



Imports System.Security.Cryptography
Namespace Runplus.Utils.Encoder
'************************************************
'* https://www.runplus.studio/Utils/Encoder '* Likun@Runplus.cn
'************************************************
Module XOREncoder
Sub Main()
'示例代码
Dim Ret As String = "" '定义返回参数,以传址方式传入

If Encoder("Hello World!", "12345abcde", Ret) Then
Console.WriteLine(Ret)
Else
Console.WriteLine(Ret)
End If
If Decoder(Ret, "12345abcde", Ret) Then
Console.WriteLine(Ret)
Else
Console.WriteLine(Ret)
End If

Console.ReadLine()

End Sub
Public Function Encoder(Source As String, Key As String, ByRef Ret As String) As Boolean
Try
If Source.Length = 0 Or Key.Length = 0 Then
Ret = "明文或私钥为空,不能进行加密。"
Return False
Else
Dim ArrKey() As Byte = MakeKey(Key)
Dim ArrSource() As Byte = Text.Encoding.UTF8.GetBytes(Source)
For i As Integer = 0 To ArrSource.Length - 1 Step 32
For j As Integer = 0 To 31 Step 1
If i + j = ArrSource.Length Then
Exit For
Else
ArrSource(i + j) = ArrSource(i + j) Xor ArrKey(j)
End If
Next
Next
Ret = ConvertToBase64(ArrSource)
Return True
End If
Catch ex As Exception
Ret = ex.Message
Return False
End Try
End Function

Public Function Decoder(Source As String, key As String, ByRef Ret As String) As Boolean
Try
If Source.Length = 0 Or key.Length = 0 Then
Ret = "明文或私钥为空,不能进行加密。"
Return False
Else
Dim ArrKey() As Byte = MakeKey(key)
Dim ArrSource() As Byte = ConvertFromBase64(Source)
For i As Integer = 0 To ArrSource.Length - 1 Step 32
For j As Integer = 0 To 31 Step 1
If i + j = ArrSource.Length Then
Exit For
Else
ArrSource(i + j) = ArrSource(i + j) Xor ArrKey(j)
End If
Next
Next
Ret = Text.Encoding.UTF8.GetString(ArrSource)
Return True
End If
Catch ex As Exception
Ret = ex.Message
Return False
End Try
End Function
Private Function MakeKey(ByRef Key As String) As Byte()
If Key.Length = 0 Then
Return Nothing
Else
Return SHA256(Text.Encoding.UTF8.GetBytes(Key))
End If
End Function

Private Function SHA256(Source As Byte()) As Byte()
If Source.Length = 0 Then
Return Nothing
Else
Dim shaM As New SHA256Managed
Return shaM.ComputeHash(Source)
End If
End Function
Private Function ConvertToBase64(Source As Byte()) As String
If Source.Length = 0 Then
Return Nothing
Else
Return Convert.ToBase64String(Source).Replace("+", "*").Replace("/", "!")
End If
End Function
Private Function ConvertFromBase64(Source As String) As Byte()
If Source.Length = 0 Then
Return Nothing
Else
Return Convert.FromBase64String(Source.Replace("*", "+").Replace("!", "/"))
End If
End Function
End Module
End Namespace
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  VB.NET 加密 解密 编码