Blame view

main.go 1.5 KB
74f41102f   Marko Tikvić   first commit
1
2
3
4
5
6
7
  package aes
  
  import (
  	"crypto/aes"
  	"crypto/cipher"
  	"crypto/rand"
  	"errors"
98399d851   Marko Tikvić   cleanup
8
  	"fmt"
74f41102f   Marko Tikvić   first commit
9
10
11
12
13
14
15
16
17
  	"io"
  	mrand "math/rand"
  	"time"
  )
  
  const (
  	keySize      = 32
  	allowedRunes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  )
98399d851   Marko Tikvić   cleanup
18
  // RandomKey returns a randomly generated 32 bytes long key.
74f41102f   Marko Tikvić   first commit
19
20
21
22
23
24
25
26
27
28
29
30
31
  func RandomKey() (key []byte) {
  	mrand.Seed(time.Now().UnixNano())
  
  	key = make([]byte, keySize)
  
  	for i := range key {
  		key[i] = allowedRunes[mrand.Intn(len(allowedRunes))]
  	}
  
  	return key
  }
  
  // Encrypt encrypts plaintext with key and returns resulting bytes.
98399d851   Marko Tikvić   cleanup
32
33
34
35
36
  func Encrypt(plaintext, key []byte) ([]byte, error) {
  	if len(key) != keySize {
  		return nil, fmt.Errorf("key size invalid: %d, must be %d
  ", len(key), keySize)
  	}
74f41102f   Marko Tikvić   first commit
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
  	c, err := aes.NewCipher(key)
  	if err != nil {
  		return nil, err
  	}
  
  	gcm, err := cipher.NewGCM(c)
  	if err != nil {
  		return nil, err
  	}
  
  	nonce := make([]byte, gcm.NonceSize())
  	if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
  		return nil, err
  	}
  
  	return gcm.Seal(nonce, nonce, plaintext, nil), nil
  }
  
  // Decrypt decrypts ciphertext with key and returns resulting bytes.
98399d851   Marko Tikvić   cleanup
56
  func Decrypt(ciphertext, key []byte) ([]byte, error) {
74f41102f   Marko Tikvić   first commit
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
  	c, err := aes.NewCipher(key)
  	if err != nil {
  		return nil, err
  	}
  
  	gcm, err := cipher.NewGCM(c)
  	if err != nil {
  		return nil, err
  	}
  
  	nonceSize := gcm.NonceSize()
  	if len(ciphertext) < nonceSize {
  		return nil, errors.New("ciphertext too short")
  	}
  
  	nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
98399d851   Marko Tikvić   cleanup
73

74f41102f   Marko Tikvić   first commit
74
75
  	return gcm.Open(nil, nonce, ciphertext, nil)
  }