Selaa lähdekoodia

implement base64 decoding

Lucas Stadler 11 vuotta sitten
vanhempi
commit
7983d11f16
1 muutettua tiedostoa jossa 42 lisäystä ja 0 poistoa
  1. 42 0
      go/encode.go

+ 42 - 0
go/encode.go

@ -39,8 +39,50 @@ func base64encode(b []byte) []byte {
39 39
	return res
40 40
}
41 41
42
func decode(b byte) byte {
43
	if 'A' <= b && b <= 'Z' {
44
		return b - 'A'
45
	} else if 'a' <= b && b <= 'z' {
46
		return 26 + b - 'a'
47
	} else if '0' <= b && b <= '9' {
48
		return 52 + b - '0'
49
	} else if b == '+' {
50
		return 62
51
	} else if b == '/' {
52
		return 63
53
	} else {
54
		fmt.Println("oops")
55
		return ' '
56
	}
57
}
58
59
func base64decode(b []byte) []byte {
60
	res := make([]byte, len(b) / 4 * 3)
61
	//fmt.Println(len(b), "->", len(res))
62
	for i := 0; i < len(b); i += 4 {
63
		c1, c2, c3, c4 := decode(b[i]), decode(b[i+1]), decode(b[i+2]), decode(b[i+3])
64
		r1 := (c1 << 2) + (c2 >> 4)
65
		r2 := ((c2 ^ ((c2 >> 4) << 4)) << 4) + (c3 >> 2)
66
		r3 := ((c3 ^ ((c3 >> 2) << 2)) << 6) + c4
67
		base := i - i / 4
68
		//fmt.Print(i, base, c1, c2, c3, c4, "\t", string(b[i]), string(b[i+1]), string(b[i+2]), string(b[i+3]))
69
		//fmt.Printf("\t -> '%s' '%s' '%s'\n", string(r1), string(r2), string(r3))
70
		res[base + 0] = r1
71
		res[base + 1] = r2
72
		res[base + 2] = r3
73
	}
74
	return res
75
}
76
42 77
func main() {
43 78
	base64 := base64encode([]byte("Hello, World!  "))
44 79
	//                                          ^^     (padded to a multiple of three)
45 80
	fmt.Println(string(base64))
81
	plain := base64decode(base64)
82
	fmt.Println(string(plain))
83
84
	secret := []byte("SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t")
85
	fmt.Println(string(secret))
86
	decoded := base64decode(secret)
87
	fmt.Println(string(decoded))
46 88
}