crypto.go 960 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package crypto
  2. import (
  3. "crypto/sha256"
  4. "golang.org/x/crypto/pbkdf2"
  5. "gopkg.in/square/go-jose.v2"
  6. )
  7. const (
  8. jweEncryption = jose.A256GCM
  9. jweAlgorithm = jose.DIRECT
  10. keyLenBytes = 32 // 256-bit for AES-256
  11. keyDerivIter = 50000
  12. )
  13. func DeriveKey(password, topicURL string) []byte {
  14. salt := sha256.Sum256([]byte(topicURL))
  15. return pbkdf2.Key([]byte(password), salt[:], keyDerivIter, keyLenBytes, sha256.New)
  16. }
  17. func Encrypt(plaintext []byte, key []byte) (string, error) {
  18. enc, err := jose.NewEncrypter(jweEncryption, jose.Recipient{Algorithm: jweAlgorithm, Key: key}, nil)
  19. if err != nil {
  20. return "", err
  21. }
  22. jwe, err := enc.Encrypt(plaintext)
  23. if err != nil {
  24. return "", err
  25. }
  26. return jwe.CompactSerialize()
  27. }
  28. func Decrypt(ciphertext string, key []byte) ([]byte, error) {
  29. jwe, err := jose.ParseEncrypted(ciphertext)
  30. if err != nil {
  31. return nil, err
  32. }
  33. out, err := jwe.Decrypt(key)
  34. if err != nil {
  35. return nil, err
  36. }
  37. return out, nil
  38. }