rsa.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package rsa
  2. import (
  3. "crypto/rand"
  4. "crypto/rsa"
  5. "crypto/x509"
  6. "encoding/pem"
  7. "errors"
  8. )
  9. var (
  10. ErrPrivateKey = errors.New("private key error")
  11. ErrPublicKey = errors.New("public key error")
  12. )
  13. func PrivateKey(pri []byte) (*rsa.PrivateKey, error) {
  14. block, _ := pem.Decode(pri)
  15. if block == nil {
  16. return nil, ErrPrivateKey
  17. }
  18. return x509.ParsePKCS1PrivateKey(block.Bytes)
  19. }
  20. func PublicKey(pub []byte) (*rsa.PublicKey, error) {
  21. block, _ := pem.Decode(pub)
  22. if block == nil {
  23. return nil, ErrPublicKey
  24. }
  25. pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
  26. if err != nil {
  27. return nil, err
  28. }
  29. rsaPub := pubInterface.(*rsa.PublicKey)
  30. return rsaPub, nil
  31. }
  32. func Encrypt(orig, pubKey []byte) ([]byte, error) {
  33. pub, err := PublicKey([]byte(pubKey))
  34. if err != nil {
  35. return nil, err
  36. }
  37. cipher, err := rsa.EncryptPKCS1v15(rand.Reader, pub, orig)
  38. if err != nil {
  39. return nil, err
  40. }
  41. return cipher, nil
  42. }
  43. func Decrypt(cipher, priKey []byte) ([]byte, error) {
  44. pri, err := PrivateKey([]byte(priKey))
  45. if err != nil {
  46. return nil, err
  47. }
  48. ori, err := rsa.DecryptPKCS1v15(nil, pri, cipher)
  49. if err != nil {
  50. return nil, err
  51. }
  52. return ori, nil
  53. }
  54. func GenerateKey(bits int) (priKey, pubKey []byte, err error) {
  55. privateKey, err := rsa.GenerateKey(rand.Reader, bits)
  56. if err != nil {
  57. return
  58. }
  59. derStream := x509.MarshalPKCS1PrivateKey(privateKey)
  60. block := &pem.Block{
  61. Type: "RSA PRIVATE KEY",
  62. Bytes: derStream,
  63. }
  64. priKey = pem.EncodeToMemory(block)
  65. publicKey := &privateKey.PublicKey
  66. derPkix, err := x509.MarshalPKIXPublicKey(publicKey)
  67. if err != nil {
  68. return
  69. }
  70. block = &pem.Block{
  71. Type: "PUBLIC KEY",
  72. Bytes: derPkix,
  73. }
  74. pubKey = pem.EncodeToMemory(block)
  75. return
  76. }