rsa.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. log.Printf("can not public")
  43. return nil, err
  44. }
  45. pub := pubInterface.(*rsa.PublicKey)
  46. return rsa.EncryptPKCS1v15(rand.Reader, pub, origData)
  47. }
  48. func RsaDecrypt(ciphertext []byte) ([]byte, error) {
  49. block, _ := pem.Decode(privateKey)
  50. if block == nil {
  51. return nil, errors.New("private key error!")
  52. }
  53. priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
  54. if err != nil {
  55. return nil, err
  56. }
  57. return rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext)
  58. }