Bytes as text: Base64 and hexadecimal
Bytes can hold any value, but an e-mail, a JSON file or a URL accepts only text. Base64 and hexadecimal turn bytes into safe letters and digits and back. This lesson encodes and decodes both, looks at the size and the padding, the form for URLs, wrong input and data URIs.
What you will learn#
- Base64: 3 bytes become 4 characters, and
=fills the end, - the padding and the size of the result,
- sending all 256 byte values through text,
- the URL-safe form (
-and_, no=), - hexadecimal with
Convert.ToHexStringandFromHexString, - the errors of wrong input,
- data URIs, and a hash written in hexadecimal.
The tutorial URLs and encodings used Base64 for one purpose. This lesson looks at the encodings themselves.
The program#
# bytes as text - Base64, Base64 for URLs and hexadecimal: encoding and decoding, the size of the result, line breaks, and data URIs
load "dotnet.ring"
using {
"System"
"System.Text"
"System.Security.Cryptography"
}
func main
oConvert = new Convert()
# Bytes can hold any value from 0 to 255, but many places accept only TEXT: an e-mail, a JSON file, a URL, an XML attribute. An
# ENCODING turns bytes into letters and digits that are safe in such places, and back. The two common ones are Base64 and hexadecimal.
cData = "Ring + .NET"
# 1. Base64: 3 bytes become 4 characters from A-Z a-z 0-9 + /, and = fills the end. The result is a third longer than the bytes.
? "1. Base64 of '" + cData + "':"
cBase64 = toBase64(cData)
? " " + cBase64 + " (" + len(cData) + " bytes -> " + len(cBase64) + " characters)"
? " decoded again: " + fromBase64(cBase64) + " same as before: " + yesNo(fromBase64(cBase64) = cData)
# 2. The padding: the number of = at the end shows how many bytes were missing in the last group of three
? nl + "2. the padding for 1, 2 and 3 bytes:"
for cText in [ "a", "ab", "abc", "abcd" ]
? " " + padRight(cText,6) + padRight(toBase64(cText),10) + "(" + len(cText) + " bytes)"
next
# 3. Any bytes, including the ones that are not text: all the 256 byte values go through Base64 and come back
cEveryByte = ""
for i = 0 to 255
cEveryByte += char(i)
next
cEncoded = toBase64(cEveryByte)
? nl + "3. all 256 byte values: " + len(cEveryByte) + " bytes -> " + len(cEncoded) + " characters, back again the same: " + yesNo(fromBase64(cEncoded) = cEveryByte)
# 4. Base64 for URLs and file names. The signs + and / have a meaning in a URL, so they are replaced by - and _, and the = is
# left out. The bytes 251 255 show the difference.
cSpecial = char(251) + char(255)
cStandard = toBase64(cSpecial)
cUrlSafe = substr(substr(substr(cStandard,"+","-"),"/","_"),"=","")
? nl + "4. the bytes 251 255:"
? " standard Base64: " + cStandard
? " for URLs: " + cUrlSafe + " (+ becomes -, / becomes _, and the = is dropped)"
# A decoder for the URL form must put the signs back and add the padding
? " decoded again: " + yesNo(fromBase64(addPadding(substr(substr(cUrlSafe,"-","+"),"_","/"))) = cSpecial)
# 5. Hexadecimal: each byte becomes two characters 0-9 A-F. The result is twice as long, but it is easy to read and to compare.
cHex = oConvert.ToHexString(cData)
? nl + "5. hexadecimal of '" + cData + "': " + cHex + " (" + len(cData) + " bytes -> " + len(cHex) + " characters)"
? " decoded again: " + oConvert.FromHexString(cHex)
? " the hexadecimal of the bytes 0, 15, 16 and 255: " + oConvert.ToHexString(char(0) + char(15) + char(16) + char(255))
# 6. A wrong text raises an error: a character that is not in the alphabet, or a hexadecimal text with an odd length
? nl + "6. wrong input:"
? " Base64 'not base64!': " + tryDecode("not base64!")
? " hexadecimal 'ABC' (odd length): " + tryHex("ABC")
# 7. A data URI puts a small file inside the text of a page or a style sheet: the type, the word base64 and the Base64 text
cDataUri = "data:text/plain;base64," + toBase64("Hello")
? nl + "7. a data URI: " + cDataUri
# 8. Where each one is used: Base64 for e-mail attachments, certificates, JSON that carries bytes, and tokens; hexadecimal for hashes,
# colors and the bytes in a debugger
? nl + "8. the SHA-256 hash of 'abc' in hexadecimal:"
? " " + hashHex("abc")
func toBase64 cBytes
return new Convert().ToBase64String(cBytes)
func fromBase64 cText
return new Convert().FromBase64String(cText)
# a Base64 text needs a length that is a multiple of 4: = fills the missing places
func addPadding cText
nMissing = (4 - len(cText) % 4) % 4
return cText + copy("=",nMissing)
func tryDecode cText
try
fromBase64(cText)
return "decoded"
catch
return errorKind(cCatchError)
done
func tryHex cText
try
new Convert().FromHexString(cText)
return "decoded"
catch
return errorKind(cCatchError)
done
func hashHex cText
return new Convert().ToHexString(new SHA256().HashData(cText))
func errorKind cMessage
cText = trim(cMessage)
nStart = substr(cText,"DotNet Error: ")
if nStart > 0
cText = substr(cText,nStart + 14)
ok
nEnd = substr(cText,":")
if nEnd > 0
cText = left(cText,nEnd - 1)
ok
return cText
func yesNo lValue
if lValue
return "yes"
ok
return "no"
func padRight cText,nWidth
return cText + copy(" ",nWidth - len(cText))1. Base64 of 'Ring + .NET':
UmluZyArIC5ORVQ= (11 bytes -> 16 characters)
decoded again: Ring + .NET same as before: yes
2. the padding for 1, 2 and 3 bytes:
a YQ== (1 bytes)
ab YWI= (2 bytes)
abc YWJj (3 bytes)
abcd YWJjZA== (4 bytes)
3. all 256 byte values: 256 bytes -> 344 characters, back again the same: yes
4. the bytes 251 255:
standard Base64: +/8=
for URLs: -_8 (+ becomes -, / becomes _, and the = is dropped)
decoded again: yes
5. hexadecimal of 'Ring + .NET': 52696E67202B202E4E4554 (11 bytes -> 22 characters)
decoded again: Ring + .NET
the hexadecimal of the bytes 0, 15, 16 and 255: 000F10FF
6. wrong input:
Base64 'not base64!': System.FormatException
hexadecimal 'ABC' (odd length): System.FormatException
7. a data URI: data:text/plain;base64,SGVsbG8=
8. the SHA-256 hash of 'abc' in hexadecimal:
BA7816BF8F01CFEA414140DE5DAE2223B00361A396177A9CB410FF61F20015ADHow it works#
Base64#
Base64 takes the bytes in groups of three (24 bits) and writes each group as four characters of 6 bits, taken from A-Z, a-z, 0-9, + and /. The result is a third longer than the data: 11 bytes become 16 characters. Convert.ToBase64String and FromBase64String are static methods, called through new Convert(). A byte[] is a Ring text of bytes in this package, so the text goes in and comes out as it is.
Padding#
When the data is not a multiple of three bytes, the last group is short and the result is filled with =: one byte gives ==, two bytes give =, three give none. The number of = tells how many bytes were missing. A decoder needs the length to be a multiple of four, which is why the function addPadding exists for texts that lost their =.
Any bytes#
Base64 works for every byte value, not only for text: step 3 sends all 256 values through and gets the same bytes back. This is why Base64 is used for pictures in JSON, for attachments in e-mail and for keys and certificates.
Base64 for URLs#
The signs + and / have a meaning in URLs and in file names, and = separates values. The URL-safe form replaces + with -, / with _, and leaves out the =. The bytes 251 255 show it: +/8= becomes -_8. A decoder puts the signs back and adds the padding again. Tokens in links, the parts of a JSON Web Token and file names made from hashes use this form.
Hexadecimal#
Convert.ToHexString writes each byte as two digits (0-9, A-F): the result is twice as long as the data, but a person can read it and compare it. 000F10FF shows the bytes 0, 15, 16 and 255; the zeros in front are part of the text. Hashes, color codes and the dumps of a debugger use hexadecimal.
Wrong input#
A character that is not in the alphabet (! and a space in not base64!) or a hexadecimal text of an odd length raises System.FormatException. A program that decodes text from outside uses try and catch and treats the error as this is not valid data.
Data URIs#
A data URI puts a small file into the text of a page or a style sheet: data:text/plain;base64,SGVsbG8= has the type, the word base64 and the Base64 text. It saves a request for small pictures but makes the page bigger by a third, so it is for tiny files only.
Base64 and hexadecimal are encodings, not encryption: anyone can decode them. Do not use them to hide a password (the tutorial Hashing and encryption).
What you learned#
- Base64 and its padding and size,
- the URL-safe form,
- hexadecimal with
ToHexStringandFromHexString, - the error of wrong input,
- data URIs.
Exercises#
- Write
toBase64Url(bytes)andfromBase64Url(text)as one function each. - Encode a small PNG file and make a data URI of it (
data:image/png;base64,...). - Write a hex dump that prints 16 bytes per line with the offset (the tutorial Binary files has one).
- Compare the lengths of Base64 and hexadecimal for 1000 bytes.