Base64 Encoding
Encodes data with MIME base64. This encoding is designed to make binary data survive transport through transport layers that are not 8-bit clean, such as mail bodies.
Public Shared Function Base64Encoding(data As Byte()) As Char()
Dim length As Integer, length2 As Integer
Dim blockCount As Integer
Dim paddingCount As Integer
length = data.Length
If (length Mod 3) = 0 Then
paddingCount = 0
blockCount = length \ 3
Else
paddingCount = 3 - (length Mod 3)
blockCount = (length + paddingCount) \ 3
End If
length2 = length + paddingCount
Dim source2 As Byte()
source2 = New Byte(length2 - 1) {}
For x As Integer = 0 To length2 - 1
If x < length Then
source2(x) = data(x)
Else
source2(x) = 0
End If
Next
Dim b1 As Byte, b2 As Byte, b3 As Byte
Dim temp As Byte, temp1 As Byte, temp2 As Byte, temp3 As Byte, temp4 As Byte
Dim buffer As Byte() = New Byte(blockCount * 4 - 1) {}
Dim result As Char() = New Char(blockCount * 4 - 1) {}
For x As Integer = 0 To blockCount - 1
b1 = source2(x * 3)
b2 = source2(x * 3 + 1)
b3 = source2(x * 3 + 2)
temp1 = CByte((b1 And 252) >> 2)
temp = CByte((b1 And 3) << 4)
temp2 = CByte((b2 And 240) >> 4)
temp2 += temp
temp = CByte((b2 And 15) << 2)
temp3 = CByte((b3 And 192) >> 6)
temp3 += temp
temp4 = CByte(b3 And 63)
buffer(x * 4) = temp1
buffer(x * 4 + 1) = temp2
buffer(x * 4 + 2) = temp3
buffer(x * 4 + 3) = temp4
Next
For x As Integer = 0 To blockCount * 4 - 1
result(x) = SixBitToChar(buffer(x))
Next
Select Case paddingCount
Case 0
Exit Select
Case 1
result(blockCount * 4 - 1) = "="c
Exit Select
Case 2
result(blockCount * 4 - 1) = "="c
result(blockCount * 4 - 2) = "="c
Exit Select
Case Else
Exit Select
End Select
Return result
End Function
Private Shared Function SixBitToChar(b As Byte) As Char
Dim lookupTable As Char() = New Char(63) {"A"c, "B"c, "C"c, "D"c, "E"c, "F"c, _
"G"c, "H"c, "I"c, "J"c, "K"c, "L"c, _
"M"c, "N"c, "O"c, "P"c, "Q"c, "R"c, _
"S"c, "T"c, "U"c, "V"c, "W"c, "X"c, _
"Y"c, "Z"c, "a"c, "b"c, "c"c, "d"c, _
"e"c, "f"c, "g"c, "h"c, "i"c, "j"c, _
"k"c, "l"c, "m"c, "n"c, "o"c, "p"c, _
"q"c, "r"c, "s"c, "t"c, "u"c, "v"c, _
"w"c, "x"c, "y"c, "z"c, "0"c, "1"c, _
"2"c, "3"c, "4"c, "5"c, "6"c, "7"c, _
"8"c, "9"c, "+"c, "/"c}
If (b >= 0) AndAlso (b <= 63) Then
Return lookupTable(CInt(b))
Else
Return " "c
End If
End Function
Example
Dim data = System.Text.Encoding.Default.GetBytes("jdfgsdhfsdfsd 6445dsfsd7fg/*/+bfjsdgf%$^")
Dim value = Base64Encoding(data)
Output
amRmZ3NkaGZzZGZzZCA2NDQ1ZHNmc2Q3ZmcvKi8rYmZqc2RnZiUkXg==