crypto.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package crypto
  2. import (
  3. "crypto/aes"
  4. "crypto/cipher"
  5. "crypto/rand"
  6. "encoding/hex"
  7. "errors"
  8. "io"
  9. )
  10. func MakeKey() []byte {
  11. key := [32]byte{}
  12. _, err := io.ReadFull(rand.Reader, key[:])
  13. if err != nil {
  14. panic(err)
  15. }
  16. return key[:]
  17. }
  18. func MakeID() (string, error) {
  19. id := [16]byte{}
  20. _, err := io.ReadFull(rand.Reader, id[:])
  21. if err != nil {
  22. return "", err
  23. }
  24. return hex.EncodeToString(id[:]), nil
  25. }
  26. func Encrypt(plaintext []byte, key []byte) ([]byte, error) {
  27. block, err := aes.NewCipher(key)
  28. if err != nil {
  29. return nil, err
  30. }
  31. gcm, err := cipher.NewGCM(block)
  32. if err != nil {
  33. return nil, err
  34. }
  35. nonce := make([]byte, gcm.NonceSize())
  36. _, err = io.ReadFull(rand.Reader, nonce)
  37. if err != nil {
  38. return nil, err
  39. }
  40. return gcm.Seal(nonce, nonce, plaintext, nil), nil
  41. }
  42. func Decrypt(ciphertext, key []byte) ([]byte, error) {
  43. block, err := aes.NewCipher(key)
  44. if err != nil {
  45. return nil, err
  46. }
  47. gcm, err := cipher.NewGCM(block)
  48. if err != nil {
  49. return nil, err
  50. }
  51. if len(ciphertext) < gcm.NonceSize() {
  52. return nil, errors.New("malformed ciphertext")
  53. }
  54. return gcm.Open(nil,
  55. ciphertext[:gcm.NonceSize()],
  56. ciphertext[gcm.NonceSize():],
  57. nil,
  58. )
  59. }