crypt.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package utils
  15. import (
  16. "crypto"
  17. "crypto/aes"
  18. "crypto/cipher"
  19. "crypto/rand"
  20. "crypto/rsa"
  21. "crypto/sha256"
  22. "crypto/x509"
  23. "encoding/base64"
  24. "encoding/pem"
  25. "fmt"
  26. "io"
  27. )
  28. // https://stackoverflow.com/questions/23897809/different-results-in-go-and-pycrypto-when-using-aes-cfb
  29. // CFB stream with 8 bit segment size
  30. // See http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf
  31. type cfb8 struct {
  32. b cipher.Block
  33. blockSize int
  34. in []byte
  35. out []byte
  36. decrypt bool
  37. }
  38. func (x *cfb8) XORKeyStream(dst, src []byte) {
  39. for i := range src {
  40. x.b.Encrypt(x.out, x.in)
  41. copy(x.in[:x.blockSize-1], x.in[1:])
  42. if x.decrypt {
  43. x.in[x.blockSize-1] = src[i]
  44. }
  45. dst[i] = src[i] ^ x.out[0]
  46. if !x.decrypt {
  47. x.in[x.blockSize-1] = dst[i]
  48. }
  49. }
  50. }
  51. // NewCFB8Encrypter returns a Stream which encrypts with cipher feedback mode
  52. // (segment size = 8), using the given Block. The iv must be the same length as
  53. // the Block's block size.
  54. func newCFB8Encrypter(block cipher.Block, iv []byte) cipher.Stream {
  55. return newCFB8(block, iv, false)
  56. }
  57. // NewCFB8Decrypter returns a Stream which decrypts with cipher feedback mode
  58. // (segment size = 8), using the given Block. The iv must be the same length as
  59. // the Block's block size.
  60. func newCFB8Decrypter(block cipher.Block, iv []byte) cipher.Stream {
  61. return newCFB8(block, iv, true)
  62. }
  63. func newCFB8(block cipher.Block, iv []byte, decrypt bool) cipher.Stream {
  64. blockSize := block.BlockSize()
  65. if len(iv) != blockSize {
  66. // stack trace will indicate whether it was de or encryption
  67. panic("cipher.newCFB: IV length must equal block size")
  68. }
  69. x := &cfb8{
  70. b: block,
  71. blockSize: blockSize,
  72. out: make([]byte, blockSize),
  73. in: make([]byte, blockSize),
  74. decrypt: decrypt,
  75. }
  76. copy(x.in, iv)
  77. return x
  78. }
  79. func toAESKey(key string) []byte {
  80. k := []byte(key)
  81. if len(k) > 32 {
  82. return k[0:32]
  83. } else {
  84. for len(k) < 32 {
  85. k = append(k, '$')
  86. }
  87. return k
  88. }
  89. }
  90. func descryptAES(k, secret []byte) ([]byte, error) {
  91. block, err := aes.NewCipher(k)
  92. if err != nil {
  93. return nil, err
  94. }
  95. if len(secret) < aes.BlockSize {
  96. return nil, fmt.Errorf("ciphertext too short")
  97. }
  98. iv := secret[:aes.BlockSize]
  99. ciphertext := secret[aes.BlockSize:]
  100. stream := newCFB8Decrypter(block, iv)
  101. stream.XORKeyStream(ciphertext, ciphertext)
  102. return ciphertext, nil
  103. }
  104. func encryptAES(k, msg []byte) ([]byte, error) {
  105. block, err := aes.NewCipher(k)
  106. if err != nil {
  107. return nil, err
  108. }
  109. cipherText := make([]byte, aes.BlockSize+len(msg))
  110. iv := cipherText[:aes.BlockSize]
  111. if _, err = io.ReadFull(rand.Reader, iv); err != nil {
  112. return nil, err
  113. }
  114. stream := newCFB8Encrypter(block, iv)
  115. stream.XORKeyStream(cipherText[aes.BlockSize:], msg)
  116. return cipherText, nil
  117. }
  118. func DescryptAESBase64(key, secret string) (string, error) {
  119. s, e := base64.StdEncoding.DecodeString(secret)
  120. if e != nil {
  121. return "", e
  122. }
  123. k := toAESKey(key)
  124. result, e := descryptAES(k, s)
  125. if e != nil {
  126. return "", e
  127. }
  128. return string(result), nil
  129. }
  130. func DescryptAESBase64Url(key, secret string) (string, error) {
  131. s, e := base64.URLEncoding.DecodeString(secret)
  132. if e != nil {
  133. return "", e
  134. }
  135. k := toAESKey(key)
  136. result, e := descryptAES(k, s)
  137. if e != nil {
  138. return "", e
  139. }
  140. return string(result), nil
  141. }
  142. func EncryptAESBase64(key, msg string) (string, error) {
  143. k := toAESKey(key)
  144. result, err := encryptAES(k, []byte(msg))
  145. if err != nil {
  146. return "", err
  147. }
  148. return base64.StdEncoding.EncodeToString(result), nil
  149. }
  150. func EncryptAESBase64Url(key, msg string) (string, error) {
  151. k := toAESKey(key)
  152. result, err := encryptAES(k, []byte(msg))
  153. if err != nil {
  154. return "", err
  155. }
  156. return base64.URLEncoding.EncodeToString(result), nil
  157. }
  158. // RSA 加密
  159. func rsaEncrypt(publicKey, origData []byte) ([]byte, error) {
  160. block, _ := pem.Decode(publicKey)
  161. if block == nil {
  162. return nil, fmt.Errorf("public key error")
  163. }
  164. pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
  165. if err != nil {
  166. return nil, err
  167. }
  168. pub := pubInterface.(*rsa.PublicKey)
  169. return rsa.EncryptPKCS1v15(rand.Reader, pub, origData)
  170. }
  171. // Base64封装的 RSA 密文解密
  172. func RsaEncryptBase64(publicKey []byte, origData string) (string, error) {
  173. data := []byte(origData)
  174. s, e := rsaEncrypt(publicKey, data)
  175. if e != nil {
  176. return "", e
  177. }
  178. result := base64.StdEncoding.EncodeToString(s)
  179. return string(result), nil
  180. }
  181. // RSA 解密
  182. func rsaDecrypt(privateKey, secret []byte) ([]byte, error) {
  183. block, _ := pem.Decode(privateKey)
  184. if block == nil {
  185. return nil, fmt.Errorf("private key error!")
  186. }
  187. priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
  188. if err != nil {
  189. return nil, err
  190. }
  191. return rsa.DecryptPKCS1v15(rand.Reader, priv, secret)
  192. }
  193. // Base64封装的 RSA 密文解密
  194. func RsaDecryptBase64(privateKey []byte, secret string) (string, error) {
  195. s, e := base64.StdEncoding.DecodeString(secret)
  196. if e != nil {
  197. return "", e
  198. }
  199. result, e := rsaDecrypt(privateKey, s)
  200. if e != nil {
  201. return "", e
  202. }
  203. return string(result), nil
  204. }
  205. // RSA 签名
  206. func RsaSign(privateKey []byte, message string) (string, error) {
  207. block, _ := pem.Decode(privateKey)
  208. if block == nil {
  209. return "", fmt.Errorf("private key error!")
  210. }
  211. priv, e := x509.ParsePKCS1PrivateKey(block.Bytes)
  212. if e != nil {
  213. return "", e
  214. }
  215. h := sha256.New()
  216. h.Write([]byte(message))
  217. d := h.Sum(nil)
  218. sign, e := rsa.SignPKCS1v15(rand.Reader, priv, crypto.SHA256, d)
  219. return string(sign), e
  220. }
  221. // RSA 签名验证
  222. func RsaUnsign(publicKey []byte, message, sign string) error {
  223. block, _ := pem.Decode(publicKey)
  224. if block == nil {
  225. return fmt.Errorf("private key error!")
  226. }
  227. pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
  228. if err != nil {
  229. return err
  230. }
  231. pub := pubInterface.(*rsa.PublicKey)
  232. h := sha256.New()
  233. h.Write([]byte(message))
  234. d := h.Sum(nil)
  235. return rsa.VerifyPKCS1v15(pub, crypto.SHA256, d, []byte(sign))
  236. }