Mã:
'Ta can thu vien .NET Framework(mscorlib.dll) de chuyen UTF-8 sang MD5/SHA1
'De chuyen Hex16/Base64 ta su dung thu vien Microsoft XML
'Cu the tren may tinh Euler dang test la Win 10 64bit, office 365 32bit thi Euler tich chon thu vien sau:
'Microsoft XML 6.0 (Neu Win 7 tro ve truoc thi la v2.0, tu Win 8 tro di la v6.0)
'mscorlib.dll(.NET Framework)
'Nguon bai viet: https://www.nextdoorwith.info/wp/se/imptech/vba-encode-sample/
Sub test()
'Input la data string UTF-8
Dim encoding As New utf8encoding
Dim inbytes() As Byte
Dim str As String
Dim outbytes() As Byte
Dim digester As Variant
Dim hashbytes() As Byte
'Doi tuong thi nghiem
Dim instring As String
instring = "Euler_THVBA"
Debug.Print "input : " & instring
inbytes = encoding.GetBytes_4(instring)
Debug.Print "Hex ============="
str = encodeToHex(inbytes)
Debug.Print "encode : " & str
Debug.Print "decode : " & encoding.GetString(decodeFromHex(str))
Debug.Print "Base64 =========="
str = encodeToBase64(inbytes)
Debug.Print "encode : " & str
Debug.Print "decode : " & encoding.GetString(decodeFromBase64(str))
Debug.Print "Digest =========="
Set digester = New MD5CryptoServiceProvider 'mscorlib.dllが必要
hashbytes = digester.ComputeHash_2(inbytes)
Debug.Print "MD5 : " & encodeToHex(hashbytes)
Set digester = New SHA1CryptoServiceProvider 'mscorlib.dllが必要
hashbytes = digester.ComputeHash_2(inbytes)
Debug.Print "SHA-1 : " & encodeToHex(hashbytes)
Set digester = New SHA256Managed 'mscorlib.dllが必要
hashbytes = digester.ComputeHash_2(inbytes)
Debug.Print "SHA-256: " & encodeToHex(hashbytes)
End Sub
'Chuyen sang Hex 16
Function encodeToHex(bytes() As Byte)
encodeToHex = encode("bin.Hex", bytes)
End Function
'Chuyen sang Base74
Function encodeToBase64(bytes() As Byte)
encodeToBase64 = encode("bin.base64", bytes)
End Function
'Giai ma Hex16
Function decodeFromHex(text As String)
decodeFromHex = decode("bin.Hex", text)
End Function
'Giai ma BASE64
Function decodeFromBase64(text As String)
decodeFromBase64 = decode("bin.base64", text)
End Function
'Ma hoa
Function encode(dataType As String, bytes() As Byte)
Dim oXmlDoc As New DOMDocument60 'Can khai bao thu vien Microsoft XML
With oXmlDoc
.LoadXML ("<root />")
.DocumentElement.dataType = dataType
.DocumentElement.nodeTypedValue = bytes
End With
encode = Replace(oXmlDoc.DocumentElement.text, vbLf, "")
End Function
'Giai ma
Function decode(dataType As String, text As String)
Dim oXmlDoc As New DOMDocument60 'Can khai bao thu vien Microsoft XML
With oXmlDoc
.LoadXML ("<root />")
.DocumentElement.dataType = dataType
.DocumentElement.text = text
End With
decode = oXmlDoc.DocumentElement.nodeTypedValue
End Function
Mã:
input : Euler_THVBA
Hex =============
encode : 45756c65725f5448564241
decode : Euler_THVBA
Base64 ==========
encode : RXVsZXJfVEhWQkE=
decode : Euler_THVBA
Digest ==========
MD5 : 0196608ee43c9ef6a8cf4a2a3b34be9f
SHA-1 : 5e8be63560441aec253d7dd49a712df8c179def6
SHA-256: 1e22772a84dcd78f95e05ac41376d08112fb2b5b44aef56eab93ceacf0659745