rsa.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. package crypto4go
  2. import (
  3. "bytes"
  4. "crypto"
  5. "crypto/rand"
  6. "crypto/rsa"
  7. "crypto/x509"
  8. "encoding/pem"
  9. "errors"
  10. "strings"
  11. )
  12. const (
  13. kPublicKeyPrefix = "-----BEGIN PUBLIC KEY-----"
  14. kPublicKeySuffix = "-----END PUBLIC KEY-----"
  15. kPKCS1Prefix = "-----BEGIN RSA PRIVATE KEY-----"
  16. KPKCS1Suffix = "-----END RSA PRIVATE KEY-----"
  17. kPKCS8Prefix = "-----BEGIN PRIVATE KEY-----"
  18. KPKCS8Suffix = "-----END PRIVATE KEY-----"
  19. kPublicKeyType = "PUBLIC KEY"
  20. kPrivateKeyType = "PRIVATE KEY"
  21. kRSAPrivateKeyType = "RSA PRIVATE KEY"
  22. )
  23. var (
  24. ErrPrivateKeyFailedToLoad = errors.New("crypto4go: private key failed to load")
  25. ErrPublicKeyFailedToLoad = errors.New("crypto4go: public key failed to load")
  26. )
  27. func FormatPublicKey(raw string) []byte {
  28. return formatKey(raw, kPublicKeyPrefix, kPublicKeySuffix, 64)
  29. }
  30. func FormatPKCS1PrivateKey(raw string) []byte {
  31. raw = strings.Replace(raw, kPKCS8Prefix, "", 1)
  32. raw = strings.Replace(raw, KPKCS8Suffix, "", 1)
  33. return formatKey(raw, kPKCS1Prefix, KPKCS1Suffix, 64)
  34. }
  35. func FormatPKCS8PrivateKey(raw string) []byte {
  36. raw = strings.Replace(raw, kPKCS1Prefix, "", 1)
  37. raw = strings.Replace(raw, KPKCS1Suffix, "", 1)
  38. return formatKey(raw, kPKCS8Prefix, KPKCS8Suffix, 64)
  39. }
  40. func ParsePKCS1PrivateKey(data []byte) (key *rsa.PrivateKey, err error) {
  41. var block *pem.Block
  42. block, _ = pem.Decode(data)
  43. if block == nil {
  44. return nil, ErrPrivateKeyFailedToLoad
  45. }
  46. key, err = x509.ParsePKCS1PrivateKey(block.Bytes)
  47. if err != nil {
  48. return nil, err
  49. }
  50. return key, err
  51. }
  52. func ParsePKCS8PrivateKey(data []byte) (key *rsa.PrivateKey, err error) {
  53. var block *pem.Block
  54. block, _ = pem.Decode(data)
  55. if block == nil {
  56. return nil, ErrPrivateKeyFailedToLoad
  57. }
  58. rawKey, err := x509.ParsePKCS8PrivateKey(block.Bytes)
  59. if err != nil {
  60. return nil, err
  61. }
  62. key, ok := rawKey.(*rsa.PrivateKey)
  63. if ok == false {
  64. return nil, ErrPrivateKeyFailedToLoad
  65. }
  66. return key, err
  67. }
  68. func ParsePublicKey(data []byte) (key *rsa.PublicKey, err error) {
  69. var block *pem.Block
  70. block, _ = pem.Decode(data)
  71. if block == nil {
  72. return nil, ErrPublicKeyFailedToLoad
  73. }
  74. var pubInterface interface{}
  75. pubInterface, err = x509.ParsePKIXPublicKey(block.Bytes)
  76. if err != nil {
  77. return nil, err
  78. }
  79. key, ok := pubInterface.(*rsa.PublicKey)
  80. if !ok {
  81. return nil, ErrPublicKeyFailedToLoad
  82. }
  83. return key, err
  84. }
  85. func packageData(data []byte, packageSize int) (r [][]byte) {
  86. var src = make([]byte, len(data))
  87. copy(src, data)
  88. r = make([][]byte, 0)
  89. if len(src) <= packageSize {
  90. return append(r, src)
  91. }
  92. for len(src) > 0 {
  93. var p = src[:packageSize]
  94. r = append(r, p)
  95. src = src[packageSize:]
  96. if len(src) <= packageSize {
  97. r = append(r, src)
  98. break
  99. }
  100. }
  101. return r
  102. }
  103. // RSAEncrypt 使用公钥 key 对数据 data 进行 RSA 加密
  104. func RSAEncrypt(plaintext, key []byte) ([]byte, error) {
  105. pubKey, err := ParsePublicKey(key)
  106. if err != nil {
  107. return nil, err
  108. }
  109. return RSAEncryptWithKey(plaintext, pubKey)
  110. }
  111. // RSAEncryptWithKey 使用公钥 key 对数据 data 进行 RSA 加密
  112. func RSAEncryptWithKey(plaintext []byte, key *rsa.PublicKey) ([]byte, error) {
  113. var pData = packageData(plaintext, key.N.BitLen()/8-11)
  114. var ciphertext = make([]byte, 0, 0)
  115. for _, d := range pData {
  116. var c, e = rsa.EncryptPKCS1v15(rand.Reader, key, d)
  117. if e != nil {
  118. return nil, e
  119. }
  120. ciphertext = append(ciphertext, c...)
  121. }
  122. return ciphertext, nil
  123. }
  124. // RSADecryptWithPKCS1 使用私钥 key 对数据 data 进行 RSA 解密,key 的格式为 pkcs1
  125. func RSADecryptWithPKCS1(ciphertext, key []byte) ([]byte, error) {
  126. priKey, err := ParsePKCS1PrivateKey(key)
  127. if err != nil {
  128. return nil, err
  129. }
  130. return RSADecryptWithKey(ciphertext, priKey)
  131. }
  132. // RSADecryptWithPKCS8 使用私钥 key 对数据 data 进行 RSA 解密,key 的格式为 pkcs8
  133. func RSADecryptWithPKCS8(ciphertext, key []byte) ([]byte, error) {
  134. priKey, err := ParsePKCS8PrivateKey(key)
  135. if err != nil {
  136. return nil, err
  137. }
  138. return RSADecryptWithKey(ciphertext, priKey)
  139. }
  140. // RSADecryptWithKey 使用私钥 key 对数据 data 进行 RSA 解密
  141. func RSADecryptWithKey(ciphertext []byte, key *rsa.PrivateKey) ([]byte, error) {
  142. var pData = packageData(ciphertext, key.PublicKey.N.BitLen()/8)
  143. var plaintext = make([]byte, 0, 0)
  144. for _, d := range pData {
  145. var p, e = rsa.DecryptPKCS1v15(rand.Reader, key, d)
  146. if e != nil {
  147. return nil, e
  148. }
  149. plaintext = append(plaintext, p...)
  150. }
  151. return plaintext, nil
  152. }
  153. func RSASignWithPKCS1(plaintext, key []byte, hash crypto.Hash) ([]byte, error) {
  154. priKey, err := ParsePKCS1PrivateKey(key)
  155. if err != nil {
  156. return nil, err
  157. }
  158. return RSASignWithKey(plaintext, priKey, hash)
  159. }
  160. func RSASignWithPKCS8(plaintext, key []byte, hash crypto.Hash) ([]byte, error) {
  161. priKey, err := ParsePKCS8PrivateKey(key)
  162. if err != nil {
  163. return nil, err
  164. }
  165. return RSASignWithKey(plaintext, priKey, hash)
  166. }
  167. func RSASignWithKey(plaintext []byte, key *rsa.PrivateKey, hash crypto.Hash) ([]byte, error) {
  168. var h = hash.New()
  169. h.Write(plaintext)
  170. var hashed = h.Sum(nil)
  171. return rsa.SignPKCS1v15(rand.Reader, key, hash, hashed)
  172. }
  173. func RSAVerify(ciphertext, sign, key []byte, hash crypto.Hash) error {
  174. pubKey, err := ParsePublicKey(key)
  175. if err != nil {
  176. return err
  177. }
  178. return RSAVerifyWithKey(ciphertext, sign, pubKey, hash)
  179. }
  180. func RSAVerifyWithKey(ciphertext, sign []byte, key *rsa.PublicKey, hash crypto.Hash) error {
  181. var h = hash.New()
  182. h.Write(ciphertext)
  183. var hashed = h.Sum(nil)
  184. return rsa.VerifyPKCS1v15(key, hash, hashed, sign)
  185. }
  186. func getPublicKeyBytes(publicKey *rsa.PublicKey) ([]byte, error) {
  187. pubDer, err := x509.MarshalPKIXPublicKey(publicKey)
  188. if err != nil {
  189. return nil, err
  190. }
  191. pubBlock := &pem.Block{Type: kPublicKeyType, Bytes: pubDer}
  192. var pubBuf bytes.Buffer
  193. if err = pem.Encode(&pubBuf, pubBlock); err != nil {
  194. return nil, err
  195. }
  196. return pubBuf.Bytes(), nil
  197. }
  198. func GenRSAKeyWithPKCS1(bits int) (privateKey, publicKey []byte, err error) {
  199. priKey, err := rsa.GenerateKey(rand.Reader, bits)
  200. if err != nil {
  201. return nil, nil, err
  202. }
  203. priDer := x509.MarshalPKCS1PrivateKey(priKey)
  204. priBlock := &pem.Block{Type: kRSAPrivateKeyType, Bytes: priDer}
  205. var priBuf bytes.Buffer
  206. if err = pem.Encode(&priBuf, priBlock); err != nil {
  207. return nil, nil, err
  208. }
  209. publicKey, err = getPublicKeyBytes(&priKey.PublicKey)
  210. if err != nil {
  211. return nil, nil, err
  212. }
  213. privateKey = priBuf.Bytes()
  214. return privateKey, publicKey, err
  215. }
  216. func GenRSAKeyWithPKCS8(bits int) (privateKey, publicKey []byte, err error) {
  217. priKey, err := rsa.GenerateKey(rand.Reader, bits)
  218. if err != nil {
  219. return nil, nil, err
  220. }
  221. priDer, err := x509.MarshalPKCS8PrivateKey(priKey)
  222. if err != nil {
  223. return nil, nil, err
  224. }
  225. priBlock := &pem.Block{Type: kPrivateKeyType, Bytes: priDer}
  226. var priBuf bytes.Buffer
  227. if err = pem.Encode(&priBuf, priBlock); err != nil {
  228. return nil, nil, err
  229. }
  230. publicKey, err = getPublicKeyBytes(&priKey.PublicKey)
  231. if err != nil {
  232. return nil, nil, err
  233. }
  234. privateKey = priBuf.Bytes()
  235. return privateKey, publicKey, err
  236. }