rsa.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package util
  2. import (
  3. "bytes"
  4. "crypto/rand"
  5. "crypto/rsa"
  6. "crypto/x509"
  7. "encoding/pem"
  8. "errors"
  9. "io"
  10. "log"
  11. "os"
  12. )
  13. var publicKey []byte
  14. var privateKey []byte
  15. func init() {
  16. publicFile, err := os.Open("rsa_public.pem")
  17. if err != nil {
  18. log.Fatalf("can not open publicFile, err: %+v", err)
  19. }
  20. publicBuf := bytes.Buffer{}
  21. if _, err := io.Copy(&publicBuf, publicFile); err != nil {
  22. log.Fatalf("can not read publicFile, err: %+v", err)
  23. }
  24. publicKey = publicBuf.Bytes()
  25. privateFile, err := os.Open("rsa_private.pem")
  26. if err != nil {
  27. log.Fatalf("can not open privateFile, err: %+v", err)
  28. }
  29. privateBuf := bytes.Buffer{}
  30. if _, err := io.Copy(&privateBuf, privateFile); err != nil {
  31. log.Fatalf("can not read privateFile, err: %+v", err)
  32. }
  33. privateKey = privateBuf.Bytes()
  34. }
  35. func RsaEncrypt(origData []byte) ([]byte, error) {
  36. block, _ := pem.Decode(publicKey)
  37. if block == nil {
  38. return nil, errors.New("public key error")
  39. }
  40. pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
  41. if err != nil {
  42. return nil, err
  43. }
  44. pub := pubInterface.(*rsa.PublicKey)
  45. return rsa.EncryptPKCS1v15(rand.Reader, pub, origData)
  46. }
  47. func RsaDecrypt(ciphertext []byte) ([]byte, error) {
  48. block, _ := pem.Decode(privateKey)
  49. if block == nil {
  50. return nil, errors.New("private key error!")
  51. }
  52. priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
  53. if err != nil {
  54. return nil, err
  55. }
  56. return rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext)
  57. }