加密與解密

來源:互聯網
上載者:User
加密|解密 Imports System.IO
Imports System.Security.Cryptography

'資料加/解密 類
Public Class CryData
'加密金鑰,初始化向量
Public ReadOnly cryKey As Byte() = {9, 4, 2, 8, 5, 1, 4, 9, 7, 6, 9, 5, 1, 13, 7, 5, 14, 9, 10, 15, 0, 1, 14, 5, 9, 4, 3, 8, 2, 10}
Public ReadOnly cryIV As Byte() = {7, 1, 8, 8, 2, 8, 7, 1, 4, 5, 6, 3, 5, 6, 7}


' 檔案加密
Public Sub EncryptData(ByVal inName As String, ByVal outName As String, _
Optional ByVal rijnKey() As Byte = Nothing, _
Optional ByVal rijnIV() As Byte = Nothing)

If rijnKey Is Nothing Then
rijnKey = cryKey


End If
If rijnIV Is Nothing Then
rijnIV = cryIV

End If
ReDim Preserve rijnKey(31)
ReDim Preserve rijnIV(15)

'Create the file streams to handle the input and output files.
Dim fin As New FileStream(inName, FileMode.Open, FileAccess.Read)
Dim fout As New FileStream(outName, FileMode.OpenOrCreate, FileAccess.ReadWrite)
fout.SetLength(0)

'Create variables to help with read and write.
Dim bin(1024) As Byte 'This is intermediate storage for the encryption.
Dim rdlen As Long = 0 'This is the total number of bytes written.
Dim totlen As Long = fin.Length 'Total length of the input file.
Dim len As Integer 'This is the number of bytes to be written at a time.
'Creates the default implementation, which is RijndaelManaged.
Dim rijn As SymmetricAlgorithm = SymmetricAlgorithm.Create()
Dim encStream As New CryptoStream(fout, _
rijn.CreateEncryptor(rijnKey, rijnIV), CryptoStreamMode.Write)

' Console.WriteLine("Encrypting...")

'Read from the input file, then encrypt and write to the output file.
While rdlen < totlen
len = fin.Read(bin, 0, 1024)
encStream.Write(bin, 0, len)
rdlen = Convert.ToInt32(rdlen + len)
' Console.WriteLine("{0} bytes processed", rdlen)
End While


'fout.Seek(0, SeekOrigin.Begin)
'Dim returnValue As String
'returnValue = New StreamReader(fout).ReadToEnd()

encStream.Close()
fout.Close()
fin.Close()

End Sub

'檔案解密

Public Sub DecryptData(ByVal inName As String, ByVal outName As String, _
Optional ByVal rijnKey() As Byte = Nothing, _
Optional ByVal rijnIV() As Byte = Nothing)

If rijnKey Is Nothing Then
rijnKey = cryKey

End If

If rijnIV Is Nothing Then
rijnIV = cryIV

End If

ReDim Preserve rijnKey(31)
ReDim Preserve rijnIV(15)

'Create the file streams to handle the input and output files.
Dim fin As New FileStream(inName, FileMode.Open, FileAccess.Read)
Dim fout As New FileStream(outName, FileMode.OpenOrCreate, _
FileAccess.ReadWrite)
fout.SetLength(0)

'Create variables to help with read and write.
Dim bin(1024) As Byte 'This is intermediate storage for the encryption.
Dim rdlen As Long = 0 'This is the total number of bytes written.
Dim totlen As Long = fin.Length 'Total length of the input file.
Dim len As Integer 'This is the number of bytes to be written at a time.
'Creates the default implementation, which is RijndaelManaged.
Dim rijn As SymmetricAlgorithm = SymmetricAlgorithm.Create()
Dim encStream As New CryptoStream(fout, _
rijn.CreateDecryptor(rijnKey, rijnIV), CryptoStreamMode.Write)

' Console.WriteLine("Encrypting...")

'Read from the input file, then encrypt and write to the output file.
While rdlen < totlen
len = fin.Read(bin, 0, 1024)
encStream.Write(bin, 0, len)
rdlen = Convert.ToInt32(rdlen + len)
' Console.WriteLine("{0} bytes processed", rdlen)

End While

encStream.Close()
fout.Close()
fin.Close()

End Sub
'檔案解密

Public Function DecryptData(ByVal inName As String, _
Optional ByVal rijnKey() As Byte = Nothing, _
Optional ByVal rijnIV() As Byte = Nothing) As String

If rijnKey Is Nothing Then
rijnKey = cryKey

End If

If rijnIV Is Nothing Then
rijnIV = cryIV

End If

ReDim Preserve rijnKey(31)
ReDim Preserve rijnIV(15)

'Create the file streams to handle the input and output files.
Dim fin As New FileStream(inName, FileMode.Open, FileAccess.Read)
' Dim fout As New FileStream(outName, FileMode.OpenOrCreate, _
' FileAccess.ReadWrite)
'儲存流,
Dim outStream As New MemoryStream() '(arrInByte, True) '(arrInByte, True)


'Create variables to help with read and write.
Dim bin(1024) As Byte 'This is intermediate storage for the encryption.
Dim rdlen As Long = 0 'This is the total number of bytes written.
Dim totlen As Long = fin.Length 'Total length of the input file.
Dim len As Integer 'This is the number of bytes to be written at a time.
'Creates the default implementation, which is RijndaelManaged.
While rdlen < totlen
len = fin.Read(bin, 0, 1024)
outStream.Write(bin, 0, len)
rdlen = Convert.ToInt32(rdlen + len)
' Console.WriteLine("{0} bytes processed", rdlen)

End While

outStream.Seek(0, SeekOrigin.Begin)

Dim rijn As SymmetricAlgorithm = SymmetricAlgorithm.Create()
Dim encStream As New CryptoStream(outStream, _
rijn.CreateDecryptor(rijnKey, rijnIV), CryptoStreamMode.Read)

' Console.WriteLine("Encrypting...")

'Read from the input file, then encrypt and write to the output file.


Dim returnValue As String
returnValue = New StreamReader(encStream, New System.Text.UnicodeEncoding()).ReadToEnd()


encStream.Close()
outStream.Close()
fin.Close()
Return returnValue

End Function





'加密
'in: inText 待加密原始文本
'in: rijnKey 32位密鑰
'in: rijnIV 16位初始化向量

'out: return 加密後的文本(為空白則加密失敗)

Public Function Crypt(ByVal inText As String, _
Optional ByVal rijnKey() As Byte = Nothing, _
Optional ByVal rijnIV() As Byte = Nothing) As String



'Create the file streams to handle the input and output files.
' Dim fin As New FileStream(inName, FileMode.Open, FileAccess.Read)
Dim arrInByte As Byte() = (New System.Text.UnicodeEncoding()).GetBytes(inText)

Dim len As Long = arrInByte.Length

If (len Mod 32) > 0 Then
Dim oldlen As Long = len

len = oldlen + 32 - oldlen Mod 32

ReDim Preserve arrInByte(len - 1)

End If

If rijnKey Is Nothing Then
rijnKey = cryKey

End If
If rijnIV Is Nothing Then
rijnIV = cryIV

End If

ReDim Preserve rijnKey(31)

ReDim Preserve rijnIV(15)


Dim outStream As New MemoryStream() '(arrInByte, True) '(arrInByte, True)

Dim rij As SymmetricAlgorithm = SymmetricAlgorithm.Create()

Dim encStream As New CryptoStream(outStream, _
rij.CreateEncryptor(rijnKey, rijnIV), _
CryptoStreamMode.Write)

encStream.Write(arrInByte, 0, len)
outStream.Seek(0, SeekOrigin.Begin)

Dim returnValue As String
returnValue = New StreamReader(outStream, New System.Text.UnicodeEncoding()).ReadToEnd()

encStream.Close()
outStream.Close()

Return returnValue

End Function

'--------------------------------------------------------------------------------------------------------
'解密

'in: inText 待解密密文
'in: rijnKey 32位解密密鑰(須跟加密時的相同)
'in: rijnIV 16位解密初始化向量(須跟加密時的相同)

'out: return 解密後的文本(為空白則解密失敗)
'解密 過程:把密文換成位元組寫到記憶體流,再跟據rijnKey和rijnIV建立解密流
'從解密流中讀取所有的資料
'--------------------------------------------------------------------------------------------------------

Public Function Decrypt(ByVal inText As String, _
Optional ByVal rijnKey() As Byte = Nothing, _
Optional ByVal rijnIV() As Byte = Nothing) As String



'密文轉換成位元組

Dim arrInByte As Byte() = (New System.Text.UnicodeEncoding()).GetBytes(inText)

'儲存流,
Dim outStream As New MemoryStream() '(arrInByte, True) '(arrInByte, True)

Dim len As Long = arrInByte.Length
If rijnKey Is Nothing Then
rijnKey = cryKey

End If

If rijnIV Is Nothing Then
rijnIV = cryIV

End If

ReDim Preserve rijnKey(31)

ReDim Preserve rijnIV(15)


Dim rij As SymmetricAlgorithm = SymmetricAlgorithm.Create()

outStream.Write(arrInByte, 0, len)

outStream.Seek(0, SeekOrigin.Begin)

Dim encStream As New CryptoStream(outStream, _
rij.CreateDecryptor(rijnKey, rijnIV), _
CryptoStreamMode.Read)

Dim returnValue As String
returnValue = New StreamReader(encStream, New System.Text.UnicodeEncoding()).ReadToEnd()


encStream.Close()
outStream.Close()

Return returnValue

End Function
End Class





' 加密
'http://community.csdn.net/Expert/topic/3199/3199494.xml?temp=.982464
Public Shared Function EncryptText(ByVal strText As String) As String
Return Encrypt(strText, "&%#@?./)")
End Function

'解密
Public Shared Function DecryptText(ByVal strText As String) As String
Return Decrypt(strText, "&%#@?./)")
End Function

'加密函數
Private Shared Function Encrypt(ByVal strText As String, ByVal strEncrKey As String) As String
Dim byKey() As Byte = {}
Dim IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}
Try
'byKey = System.Text.Encoding.UTF8.GetBytes(Left(strEncrKey, 8))
byKey = System.Text.Encoding.UTF8.GetBytes(strEncrKey.Substring(0, 8))
Dim des As New System.Security.Cryptography.DESCryptoServiceProvider
Dim inputByteArray() As Byte = System.Text.Encoding.UTF8.GetBytes(strText)
Dim ms As New MemoryStream
Dim cs As New CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write)
cs.Write(inputByteArray, 0, inputByteArray.Length)
cs.FlushFinalBlock()
Return Convert.ToBase64String(ms.ToArray())
Catch ex As Exception
Return ex.Message
End Try
End Function

'解密函數
Private Shared Function Decrypt(ByVal strText As String, ByVal sDecrKey As String) As String
Dim byKey() As Byte = {}
Dim IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}
Dim inputByteArray(strText.Length) As Byte
Try
'byKey = System.Text.Encoding.UTF8.GetBytes(Left(sDecrKey, 8))
byKey = System.Text.Encoding.UTF8.GetBytes(sDecrKey.Substring(0, 8))

Dim des As New DESCryptoServiceProvider
inputByteArray = Convert.FromBase64String(strText)
Dim ms As New MemoryStream
Dim cs As New CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write)
cs.Write(inputByteArray, 0, inputByteArray.Length)
cs.FlushFinalBlock()
Dim encoding As System.Text.Encoding = System.Text.Encoding.UTF8
Return encoding.GetString(ms.ToArray())
Catch ex As Exception
Return ex.Message
End Try
End Function






相關文章

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。