crypto.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. package utils
  2. import (
  3. "bytes"
  4. "crypto"
  5. "crypto/aes"
  6. "fmt"
  7. //"crypto/aes"
  8. "crypto/cipher"
  9. "crypto/des"
  10. "crypto/rand"
  11. "crypto/rsa"
  12. "crypto/sha1"
  13. "crypto/x509"
  14. "encoding/base64"
  15. "encoding/pem"
  16. "errors"
  17. //"io"
  18. "strings"
  19. //"fmt"
  20. )
  21. const CRYPTO_KEY = "3D28BP43U3Y1B4N6REQW3F319DD23464"
  22. //des加密
  23. func DesEncrypt(key, iv, plainText []byte) ([]byte, error) {
  24. block, err := des.NewCipher(key)
  25. if err != nil {
  26. return nil, err
  27. }
  28. blockSize := block.BlockSize()
  29. origData := pkcs5Padding(plainText, blockSize)
  30. blockMode := cipher.NewCBCEncrypter(block, iv)
  31. cryted := make([]byte, len(origData))
  32. blockMode.CryptBlocks(cryted, origData)
  33. return cryted, nil
  34. }
  35. //des解密
  36. func DesDecrypt(key, iv, cipherText []byte) ([]byte, error) {
  37. block, err := des.NewCipher(key)
  38. if err != nil {
  39. return nil, err
  40. }
  41. blockMode := cipher.NewCBCDecrypter(block, iv)
  42. origData := make([]byte, len(cipherText))
  43. blockMode.CryptBlocks(origData, cipherText)
  44. origData = pkcs5UnPadding(origData)
  45. return origData, nil
  46. }
  47. //func AesEncrypt(key []byte, plaintext string) (string, error) {
  48. // block, err := aes.NewCipher(key)
  49. // if err != nil {
  50. // return "", err
  51. // }
  52. // ciphertext := make([]byte, aes.BlockSize+len(plaintext))
  53. // iv := ciphertext[:aes.BlockSize]
  54. // if _, err := io.ReadFull(rand.Reader, iv); err != nil {
  55. // return "", err
  56. // }
  57. // cipher.NewCFBEncrypter(block, iv).XORKeyStream(ciphertext[aes.BlockSize:],
  58. // []byte(plaintext))
  59. //
  60. // return base64.StdEncoding.EncodeToString(ciphertext), nil
  61. //}
  62. //
  63. //func AesDecrypt(key []byte, cipherText string) (string, error) {
  64. // // ciphertext, err := hex.DecodeString(cipherText)
  65. // ciphertext, err := base64.StdEncoding.DecodeString(cipherText)
  66. // if err != nil {
  67. // return "", err
  68. // }
  69. // block, err := aes.NewCipher(key)
  70. // if err != nil {
  71. // return "", err
  72. // }
  73. // if len(ciphertext) < aes.BlockSize {
  74. // return "", errors.New("ciphertext too short")
  75. // }
  76. // iv := ciphertext[:aes.BlockSize]
  77. // ciphertext = ciphertext[aes.BlockSize:]
  78. // cipher.NewCFBDecrypter(block, iv).XORKeyStream(ciphertext, ciphertext)
  79. // return string(ciphertext), nil
  80. //}
  81. //
  82. //func AesEncrypt1(origData, key []byte) ([]byte, error) {
  83. // block, err := aes.NewCipher(key)
  84. // if err != nil {
  85. // return nil, err
  86. // }
  87. // blockSize := block.BlockSize()
  88. // origData = pkcs5Padding(origData, blockSize)
  89. // // origData = ZeroPadding(origData, block.BlockSize())
  90. // blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
  91. // crypted := make([]byte, len(origData))
  92. // // 根据CryptBlocks方法的说明,如下方式初始化crypted也可以
  93. // // crypted := origData
  94. // blockMode.CryptBlocks(crypted, origData)
  95. //
  96. // return crypted, nil
  97. //}
  98. //
  99. //func AesDecrypt1(crypted, key []byte) ([]byte, error) {
  100. // block, err := aes.NewCipher(key)
  101. // if err != nil {
  102. // return nil, err
  103. // }
  104. // blockSize := block.BlockSize()
  105. // blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
  106. // origData := make([]byte, len(crypted))
  107. // // origData := crypted
  108. // blockMode.CryptBlocks(origData, crypted)
  109. // origData = pkcs5UnPadding(origData)
  110. // // origData = ZeroUnPadding(origData)
  111. // return origData, nil
  112. //}
  113. //
  114. //func AesEncrypt2(origData, key []byte) ([]byte, error) {
  115. // txt := string(origData)
  116. // block, err := aes.NewCipher(key)
  117. // if err != nil {
  118. // return nil, err
  119. // }
  120. // encrypter := cipher.NewECBEncrypter(block)
  121. // blockSize := block.BlockSize()
  122. // origData = pkcs5Padding(origData, blockSize)
  123. //
  124. // dest := make([]byte, (len(txt)/len(key)+1)*len(key))
  125. // encrypter.CryptBlocks(dest, origData)
  126. // return dest, nil
  127. //}
  128. //
  129. //func AesDecrypt2(crypted, key []byte) ([]byte, error) {
  130. // block, err := aes.NewCipher(key)
  131. // if err != nil {
  132. // return nil, err
  133. // }
  134. //
  135. // blockMode := cipher.NewECBDecrypter(block)
  136. // origData := make([]byte, len(crypted))
  137. // // origData := crypted
  138. // blockMode.CryptBlocks(origData, crypted)
  139. // origData = pkcs5UnPadding(origData)
  140. // // origData = ZeroUnPadding(origData)
  141. // return origData, nil
  142. //}
  143. func RSASign(data string, privKey string) (string, error) {
  144. pemBlock, _ := pem.Decode([]byte(privKey))
  145. if pemBlock == nil {
  146. return "", errors.New("PARSE PRIVATE KEY FAILED")
  147. }
  148. if pemBlock.Type != "RSA PRIVATE KEY" {
  149. return "", errors.New("RSA PRIVATE KEY")
  150. }
  151. key, err := x509.ParsePKCS1PrivateKey(pemBlock.Bytes)
  152. if err != nil {
  153. return "", err
  154. }
  155. h := sha1.New()
  156. h.Write([]byte(data))
  157. signature, err := rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA1, h.Sum(nil))
  158. if err != nil {
  159. return "", err
  160. }
  161. return string(Base64Encode(signature)), nil
  162. }
  163. func SignPKCS1v15(src, key []byte, hash crypto.Hash) ([]byte, error) {
  164. var h = hash.New()
  165. h.Write(src)
  166. var hashed = h.Sum(nil)
  167. var err error
  168. var block *pem.Block
  169. block, _ = pem.Decode(key)
  170. if block == nil {
  171. return nil, errors.New("private key error")
  172. }
  173. var pri *rsa.PrivateKey
  174. pri, err = x509.ParsePKCS1PrivateKey(block.Bytes)
  175. if err != nil {
  176. return nil, err
  177. }
  178. return rsa.SignPKCS1v15(rand.Reader, pri, hash, hashed)
  179. }
  180. func SignRSA2(keys []string, param map[string]string, privateKey []byte) (s string, err error) {
  181. var pList = make([]string, 0, 0)
  182. for _, key := range keys {
  183. var value = strings.TrimSpace(param[key])
  184. if len(value) > 0 {
  185. pList = append(pList, key+"="+value)
  186. }
  187. }
  188. var src = strings.Join(pList, "&")
  189. sig, err := SignPKCS1v15([]byte(src), privateKey, crypto.SHA256)
  190. if err != nil {
  191. return "", err
  192. }
  193. s = base64.StdEncoding.EncodeToString(sig)
  194. return s, nil
  195. }
  196. func VerifyPKCS1v15(src, sig, key []byte, hash crypto.Hash) error {
  197. var h = hash.New()
  198. h.Write(src)
  199. var hashed = h.Sum(nil)
  200. var err error
  201. var block *pem.Block
  202. block, _ = pem.Decode(key)
  203. if block == nil {
  204. return errors.New("public key error")
  205. }
  206. var pubInterface interface{}
  207. pubInterface, err = x509.ParsePKIXPublicKey(block.Bytes)
  208. if err != nil {
  209. return err
  210. }
  211. var pub = pubInterface.(*rsa.PublicKey)
  212. return rsa.VerifyPKCS1v15(pub, hash, hashed, sig)
  213. }
  214. func pkcs5Padding(src []byte, blockSize int) []byte {
  215. padding := blockSize - len(src)%blockSize
  216. padtext := bytes.Repeat([]byte{byte(padding)}, padding)
  217. return append(src, padtext...)
  218. }
  219. func pkcs5UnPadding(src []byte) []byte {
  220. length := len(src)
  221. unpadding := int(src[length-1])
  222. return src[:(length - unpadding)]
  223. }
  224. func AesDecrypt(crypted, key []byte) ([]byte, error) {
  225. block, err := aes.NewCipher(key)
  226. if err != nil {
  227. return nil, err
  228. }
  229. blockMode := NewECBDecrypter(block)
  230. origData := make([]byte, len(crypted))
  231. blockMode.CryptBlocks(origData, crypted)
  232. origData = PKCS5UnPadding(origData)
  233. return origData, nil
  234. }
  235. func AesEncrypt(src, key string) ([]byte, error) {
  236. block, err := aes.NewCipher([]byte(key))
  237. if err != nil {
  238. return nil, err
  239. }
  240. ecb := NewECBEncrypter(block)
  241. content := []byte(src)
  242. content = PKCS5Padding(content, block.BlockSize())
  243. crypted := make([]byte, len(content))
  244. ecb.CryptBlocks(crypted, content)
  245. return crypted, nil
  246. }
  247. func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
  248. padding := blockSize - len(ciphertext)%blockSize
  249. padtext := bytes.Repeat([]byte{byte(padding)}, padding)
  250. return append(ciphertext, padtext...)
  251. }
  252. func PKCS5UnPadding(origData []byte) []byte {
  253. length := len(origData)
  254. unpadding := int(origData[length-1])
  255. return origData[:(length - unpadding)]
  256. }
  257. type ecb struct {
  258. b cipher.Block
  259. blockSize int
  260. }
  261. func newECB(b cipher.Block) *ecb {
  262. return &ecb{
  263. b: b,
  264. blockSize: b.BlockSize(),
  265. }
  266. }
  267. type ecbEncrypter ecb
  268. // NewECBEncrypter returns a BlockMode which encrypts in electronic code book mode, using the given Block.
  269. func NewECBEncrypter(b cipher.Block) cipher.BlockMode {
  270. return (*ecbEncrypter)(newECB(b))
  271. }
  272. func (x *ecbEncrypter) BlockSize() int { return x.blockSize }
  273. func (x *ecbEncrypter) CryptBlocks(dst, src []byte) {
  274. if len(src)%x.blockSize != 0 {
  275. fmt.Println("crypto/cipher: input not full blocks")
  276. return
  277. }
  278. if len(dst) < len(src) {
  279. fmt.Println("crypto/cipher: output smaller than input")
  280. return
  281. }
  282. for len(src) > 0 {
  283. x.b.Encrypt(dst, src[:x.blockSize])
  284. src = src[x.blockSize:]
  285. dst = dst[x.blockSize:]
  286. }
  287. }
  288. type ecbDecrypter ecb
  289. // NewECBDecrypter returns a BlockMode which decrypts in electronic code book mode, using the given Block.
  290. func NewECBDecrypter(b cipher.Block) cipher.BlockMode {
  291. return (*ecbDecrypter)(newECB(b))
  292. }
  293. func (x *ecbDecrypter) BlockSize() int { return x.blockSize }
  294. func (x *ecbDecrypter) CryptBlocks(dst, src []byte) {
  295. if len(src)%x.blockSize != 0 {
  296. fmt.Println("crypto/cipher: input not full blocks")
  297. return
  298. }
  299. if len(dst) < len(src) {
  300. fmt.Println("crypto/cipher: output smaller than input")
  301. return
  302. }
  303. for len(src) > 0 {
  304. x.b.Decrypt(dst, src[:x.blockSize])
  305. src = src[x.blockSize:]
  306. dst = dst[x.blockSize:]
  307. }
  308. }