rsa.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package unionpay
  2. import (
  3. "crypto"
  4. "crypto/rand"
  5. "crypto/rsa"
  6. "crypto/sha1"
  7. "crypto/sha256"
  8. )
  9. // encrypt RSA 加密
  10. func encrypt(publicKey *rsa.PublicKey, src []byte) (data []byte, err error) {
  11. data, err = rsa.EncryptPKCS1v15(rand.Reader, publicKey, src)
  12. return
  13. }
  14. // decrypt RSA 解密
  15. func decrypt(priveKey *rsa.PrivateKey, ciphertext []byte) (data []byte, err error) {
  16. data, err = rsa.DecryptPKCS1v15(rand.Reader, priveKey, ciphertext)
  17. return
  18. }
  19. // sign RSA 签名
  20. func sign(priveKey *rsa.PrivateKey, src []byte) (data []byte, err error) {
  21. hashed := sha256.Sum256(src)
  22. //hashed = sha256.Sum256(hashed[:])
  23. data, err = rsa.SignPKCS1v15(rand.Reader, priveKey, crypto.SHA256, hashed[:])
  24. return
  25. }
  26. // signsha1 RSA sha1签名
  27. func signsha1(priveKey *rsa.PrivateKey, src []byte) (data []byte, err error) {
  28. hashed := sha1.Sum(src)
  29. data, err = rsa.SignPKCS1v15(rand.Reader, priveKey, crypto.SHA1, hashed[:])
  30. return
  31. }
  32. // verify RSA 签名验证
  33. func verify(publicKey *rsa.PublicKey, src, sig []byte) (err error) {
  34. hashed := sha256.Sum256(src)
  35. err = rsa.VerifyPKCS1v15(publicKey, crypto.SHA256, hashed[:], sig)
  36. return
  37. }