main.go raw
1 package main
2
3 import (
4 "crypto/aes"
5 "crypto/hmac"
6 "crypto/rand"
7 "crypto/sha256"
8 "crypto/sha512"
9 "os"
10 )
11
12 func main() {
13 // SHA-256
14 h := sha256.New()
15 h.Write([]byte("hello moxie"))
16 sum := h.Sum(nil)
17 os.Stdout.Write([]byte("sha256: "))
18 printHex(sum)
19 os.Stdout.Write([]byte("\n"))
20
21 // SHA-512
22 h2 := sha512.New()
23 h2.Write([]byte("hello moxie"))
24 sum2 := h2.Sum(nil)
25 os.Stdout.Write([]byte("sha512: "))
26 printHex(sum2)
27 os.Stdout.Write([]byte("\n"))
28
29 // HMAC-SHA256
30 mac := hmac.New(sha256.New, []byte("secret key"))
31 mac.Write([]byte("hello moxie"))
32 macSum := mac.Sum(nil)
33 os.Stdout.Write([]byte("hmac: "))
34 printHex(macSum)
35 os.Stdout.Write([]byte("\n"))
36
37 // crypto/rand
38 random := []byte{:16:16}
39 rand.Read(random)
40 os.Stdout.Write([]byte("random: "))
41 printHex(random)
42 os.Stdout.Write([]byte("\n"))
43
44 // AES
45 key := []byte("0123456789abcdef") // 16 bytes for AES-128
46 block, err := aes.NewCipher(key)
47 if err != nil {
48 os.Stdout.Write([]byte("aes error\n"))
49 return
50 }
51 plain := []byte("attack at dawn!!") // exactly 16 bytes
52 cipher := []byte{:16:16}
53 block.Encrypt(cipher, plain)
54 os.Stdout.Write([]byte("aes: "))
55 printHex(cipher)
56 os.Stdout.Write([]byte("\n"))
57 }
58
59 func printHex(data []byte) {
60 hex := []byte("0123456789abcdef")
61 for _, b := range data {
62 os.Stdout.Write([]byte{hex[b>>4], hex[b&0x0f]})
63 }
64 }
65