rncryptor.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package rncryptor
  2. import(
  3. "bytes"
  4. "errors"
  5. "crypto/sha1"
  6. "crypto/sha256"
  7. "crypto/hmac"
  8. "crypto/aes"
  9. "crypto/cipher"
  10. "golang.org/x/crypto/pbkdf2"
  11. )
  12. func Decrypt(password string, data []byte) ([]byte, error) {
  13. version := data[:1]
  14. options := data[1:2]
  15. encSalt := data[2:10]
  16. hmacSalt := data[10:18]
  17. iv := data[18:34]
  18. cipherText := data[34:(len(data)-66+34)]
  19. expectedHmac := data[len(data)-32:len(data)]
  20. msg := make([]byte, 0)
  21. msg = append(msg, version...)
  22. msg = append(msg, options...)
  23. msg = append(msg, encSalt...)
  24. msg = append(msg, hmacSalt...)
  25. msg = append(msg, iv...)
  26. msg = append(msg, cipherText...)
  27. hmacKey := pbkdf2.Key([]byte(password), hmacSalt, 10000, 32, sha1.New)
  28. testHmac := hmac.New(sha256.New, hmacKey)
  29. testHmac.Write(msg)
  30. testHmacVal := testHmac.Sum(nil)
  31. verified := bytes.Equal(testHmacVal, expectedHmac)
  32. if !verified {
  33. return nil, errors.New("Password may be incorrect, or the data has been corrupted. (HMAC could not be verified)")
  34. }
  35. cipherKey := pbkdf2.Key([]byte(password), encSalt, 10000, 32, sha1.New)
  36. cipherBlock, err := aes.NewCipher(cipherKey)
  37. if err != nil {
  38. return nil, err
  39. }
  40. decrypted := make([]byte, len(cipherText))
  41. copy(decrypted, cipherText)
  42. decrypter := cipher.NewCBCDecrypter(cipherBlock, iv)
  43. decrypter.CryptBlocks(decrypted, decrypted)
  44. length := len(decrypted)
  45. unpadding := int(decrypted[length-1])
  46. return decrypted[:(length - unpadding)], nil
  47. }