forked from searKing/golang
/
pasta.go
77 lines (61 loc) · 1.76 KB
/
pasta.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// Copyright 2020 The searKing Author. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cryptopasta
import (
"encoding/base64"
"github.com/gtank/cryptopasta"
"github.com/pkg/errors"
)
// copy & paste-friendly golang crypto
func fixedKey(key []byte) *[32]byte {
var result [32]byte
copy(result[:], key[:32])
return &result
}
func Encrypt(plaintext []byte, keys ...[]byte) (ciphertext string, err error) {
if len(keys) == 0 {
return "", errors.Errorf("at least one encryption key must be defined but none were")
}
for _, key := range keys {
if ciphertext, err = encrypt(plaintext, key); err == nil {
return ciphertext, nil
}
}
return "", err
}
func Decrypt(ciphertext string, keys ...[]byte) (p []byte, err error) {
if len(keys) == 0 {
return nil, errors.Errorf("at least one decryption key must be defined but none were")
}
for _, key := range keys {
if p, err = decrypt(ciphertext, key); err == nil {
return p, nil
}
}
return nil, err
}
func encrypt(plaintext []byte, key []byte) (string, error) {
if len(key) != 32 {
return "", errors.Errorf("key must be exactly 32 long bytes, got %d bytes", len(key))
}
ciphertext, err := cryptopasta.Encrypt(plaintext, fixedKey(key))
if err != nil {
return "", err
}
return base64.URLEncoding.EncodeToString(ciphertext), nil
}
func decrypt(ciphertext string, key []byte) ([]byte, error) {
if len(key) != 32 {
return nil, errors.Errorf("key must be exactly 32 long bytes, got %d bytes", len(key))
}
raw, err := base64.URLEncoding.DecodeString(ciphertext)
if err != nil {
return nil, err
}
plaintext, err := cryptopasta.Decrypt(raw, fixedKey(key))
if err != nil {
return nil, err
}
return plaintext, nil
}