| 1 |
package base64 |
| 2 |
|
| 3 |
import ( |
| 4 |
"encoding/base64" |
| 5 |
) |
| 6 |
|
| 7 |
const ( |
| 8 |
StdPadding rune = base64.StdPadding |
| 9 |
NoPadding rune = base64.NoPadding |
| 10 |
|
| 11 |
encodeStd = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" |
| 12 |
encodeURL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_" |
| 13 |
encodeIMAP = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+," |
| 14 |
|
| 15 |
letterRange = int8('Z' - 'A' + 1) |
| 16 |
) |
| 17 |
|
| 18 |
// StdEncoding is the standard base64 encoding, as defined in RFC 4648. |
| 19 |
var StdEncoding = NewEncoding(encodeStd) |
| 20 |
|
| 21 |
// URLEncoding is the alternate base64 encoding defined in RFC 4648. |
| 22 |
// It is typically used in URLs and file names. |
| 23 |
var URLEncoding = NewEncoding(encodeURL) |
| 24 |
|
| 25 |
// RawStdEncoding is the standard unpadded base64 encoding defined in RFC 4648 section 3.2. |
| 26 |
// This is the same as StdEncoding but omits padding characters. |
| 27 |
var RawStdEncoding = StdEncoding.WithPadding(NoPadding) |
| 28 |
|
| 29 |
// RawURLEncoding is the unpadded alternate base64 encoding defined in RFC 4648. |
| 30 |
// This is the same as URLEncoding but omits padding characters. |
| 31 |
var RawURLEncoding = URLEncoding.WithPadding(NoPadding) |
| 32 |
|
| 33 |
// NewEncoding returns a new padded Encoding defined by the given alphabet, |
| 34 |
// which must be a 64-byte string that does not contain the padding character |
| 35 |
// or CR / LF ('\r', '\n'). Unlike the standard library, the encoding alphabet |
| 36 |
// cannot be abitrary, and it must follow one of the know standard encoding |
| 37 |
// variants. |
| 38 |
// |
| 39 |
// Required alphabet values: |
| 40 |
// * [0,26): characters 'A'..'Z' |
| 41 |
// * [26,52): characters 'a'..'z' |
| 42 |
// * [52,62): characters '0'..'9' |
| 43 |
// Flexible alphabet value options: |
| 44 |
// * RFC 4648, RFC 1421, RFC 2045, RFC 2152, RFC 4880: '+' and '/' |
| 45 |
// * RFC 4648 URI: '-' and '_' |
| 46 |
// * RFC 3501: '+' and ',' |
| 47 |
// |
| 48 |
// The resulting Encoding uses the default padding character ('='), which may |
| 49 |
// be changed or disabled via WithPadding. The padding characters is urestricted, |
| 50 |
// but it must be a character outside of the encoder alphabet. |
| 51 |
func NewEncoding(encoder string) *Encoding { |
| 52 |
if len(encoder) != 64 { |
| 53 |
panic("encoding alphabet is not 64-bytes long") |
| 54 |
} |
| 55 |
|
| 56 |
if _, ok := allowedEncoding[encoder]; !ok { |
| 57 |
panic("non-standard encoding alphabets are not supported") |
| 58 |
} |
| 59 |
|
| 60 |
return newEncoding(encoder) |
| 61 |
} |
| 62 |
|
| 63 |
var allowedEncoding = map[string]struct{}{ |
| 64 |
encodeStd: {}, |
| 65 |
encodeURL: {}, |
| 66 |
encodeIMAP: {}, |
| 67 |
} |