Base64 Decoding

Decodes data encoded with MIME base64.



									Public Shared Function Base64Decoding(data As Char()) As Byte()
	Dim length As Integer, length2 As Integer, length3 As Integer
	Dim blockCount As Integer
	Dim paddingCount As Integer = 0

	length = data.Length
	blockCount = length \ 4
	length2 = blockCount * 3

	For x As Integer = 0 To 1
		If data(length - x - 1) = "="c Then
			paddingCount += 1
		End If
	Next

	Dim buffer As Byte() = New Byte(length - 1) {}
	Dim buffer2 As Byte() = New Byte(length2 - 1) {}

	For x As Integer = 0 To length - 1
		buffer(x) = CharToSixBit(data(x))
	Next

	Dim b As Byte, b1 As Byte, b2 As Byte, b3 As Byte
	Dim temp1 As Byte, temp2 As Byte, temp3 As Byte, temp4 As Byte

	For x As Integer = 0 To blockCount - 1
		temp1 = buffer(x * 4)
		temp2 = buffer(x * 4 + 1)
		temp3 = buffer(x * 4 + 2)
		temp4 = buffer(x * 4 + 3)

		b = CByte(temp1 << 2)
		b1 = CByte((temp2 And 48) >> 4)
		b1 += b

		b = CByte((temp2 And 15) << 4)
		b2 = CByte((temp3 And 60) >> 2)
		b2 += b

		b = CByte((temp3 And 3) << 6)
		b3 = temp4
		b3 += b

		buffer2(x * 3) = b1
		buffer2(x * 3 + 1) = b2
		buffer2(x * 3 + 2) = b3
	Next

	length3 = length2 - paddingCount
	Dim result As Byte() = New Byte(length3 - 1) {}

	For x As Integer = 0 To length3 - 1
		result(x) = buffer2(x)
	Next

	Return result
End Function

Private Shared Function CharToSixBit(c As Char) As Byte
	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 c = "="c Then
		Return 0
	Else
		For x As Integer = 0 To 63
			If lookupTable(x) = c Then
				Return CByte(x)
			End If
		Next

		Return 0
	End If
End Function
								


Example

									Dim data = "amRmZ3NkaGZzZGZzZCA2NDQ1ZHNmc2Q3ZmcvKi8rYmZqc2RnZiUkXg=="
Dim value = Base64Decoding(data.ToCharArray())
								


Output

									jdfgsdhfsdfsd 6445dsfsd7fg/*/+bfjsdgf%$^