| 1 |
package yescrypt |
| 2 |
|
| 3 |
import ( |
| 4 |
"errors" |
| 5 |
) |
| 6 |
|
| 7 |
const itoa64 = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" |
| 8 |
|
| 9 |
var atoi64Partial = [...]byte{ |
| 10 |
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, |
| 11 |
64, 64, 64, 64, 64, 64, 64, |
| 12 |
12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, |
| 13 |
25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, |
| 14 |
64, 64, 64, 64, 64, 64, |
| 15 |
38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, |
| 16 |
51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, |
| 17 |
} |
| 18 |
|
| 19 |
func atoi64(c byte) int { |
| 20 |
if c >= '.' && c <= 'z' { |
| 21 |
return int(atoi64Partial[c-'.']) |
| 22 |
} |
| 23 |
|
| 24 |
return 64 |
| 25 |
} |
| 26 |
|
| 27 |
func byteEncode64(src byte) byte { |
| 28 |
return itoa64[src&0x3f] |
| 29 |
} |
| 30 |
|
| 31 |
func Encode64(src []byte) []byte { |
| 32 |
dst := make([]byte, 0, (len(src)*8+5)/6) |
| 33 |
|
| 34 |
for i := 0; i < len(src); { |
| 35 |
value, bits := uint32(0), 0 |
| 36 |
|
| 37 |
for ; bits < 24 && i < len(src); bits += 8 { |
| 38 |
value |= uint32(src[i]) << bits |
| 39 |
i++ |
| 40 |
} |
| 41 |
|
| 42 |
for ; bits > 0; bits -= 6 { |
| 43 |
dst = append(dst, itoa64[value&0x3f]) |
| 44 |
value >>= 6 |
| 45 |
} |
| 46 |
} |
| 47 |
|
| 48 |
return dst |
| 49 |
} |
| 50 |
|
| 51 |
func Decode64(src []byte) []byte { |
| 52 |
dst := make([]byte, 0, len(src)*3/4) |
| 53 |
|
| 54 |
for i := 0; i < len(src); { |
| 55 |
value, bits := uint32(0), uint32(0) |
| 56 |
|
| 57 |
for ; bits < 24 && i < len(src); bits += 6 { |
| 58 |
c := atoi64(src[i]) |
| 59 |
if c > 63 { |
| 60 |
return nil |
| 61 |
} |
| 62 |
i++ |
| 63 |
value |= uint32(c) << bits |
| 64 |
} |
| 65 |
|
| 66 |
if bits < 12 { |
| 67 |
return nil |
| 68 |
} |
| 69 |
|
| 70 |
for ; bits >= 8; bits -= 8 { |
| 71 |
dst = append(dst, byte(value)) |
| 72 |
value >>= 8 |
| 73 |
} |
| 74 |
|
| 75 |
if value != 0 { |
| 76 |
return nil |
| 77 |
} |
| 78 |
} |
| 79 |
return dst |
| 80 |
} |
| 81 |
|
| 82 |
func EncodeSetting(flags, ln, r int) []byte { |
| 83 |
|
| 84 |
return []byte("j" + string(byteEncode64(byte(ln-1))) + string(byteEncode64(byte(r-1)))) |
| 85 |
} |
| 86 |
|
| 87 |
func DecodeSetting(setting []byte) (flags, ln, r int, err error) { |
| 88 |
if len(setting) != 3 { |
| 89 |
return 0, 0, 0, errors.New("yescrypt: bad setting") |
| 90 |
} |
| 91 |
|
| 92 |
|
| 93 |
if setting[0] != byte(106) { |
| 94 |
return 0, 0, 0, errors.New("yescrypt: bad setting") |
| 95 |
} |
| 96 |
|
| 97 |
|
| 98 |
return 182, atoi64(setting[1]) + 1, atoi64(setting[2]) + 1, nil |
| 99 |
} |