encrypt_tool.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. package tool
  2. import (
  3. "bytes"
  4. "crypto/cipher"
  5. "crypto/des"
  6. "crypto/md5"
  7. "crypto/rand"
  8. "crypto/rsa"
  9. "crypto/x509"
  10. "encoding/base64"
  11. "encoding/hex"
  12. "encoding/pem"
  13. "errors"
  14. "fmt"
  15. "github.com/smartwalle/crypto4go"
  16. "log"
  17. "os"
  18. "strings"
  19. )
  20. var SysConfigDir = ""
  21. const (
  22. MD5_SALT = "keiven"
  23. )
  24. var (
  25. publicKey []byte
  26. privateKey []byte
  27. )
  28. // InitEncrypt
  29. // @Description: 初始化秘钥
  30. func InitEncrypt(pubKey, priKey string) {
  31. publicKey = []byte(pubKey)
  32. privateKey = []byte(priKey)
  33. //GenerateRSAKey(1024 * 4)
  34. }
  35. // 生成RSA私钥和公钥,保存到文件中
  36. func GenerateRSAKey(bits int) {
  37. //GenerateKey函数使用随机数据生成器random生成一对具有指定字位数的RSA密钥
  38. //Reader是一个全局、共享的密码用强随机数生成器
  39. privateKey, err := rsa.GenerateKey(rand.Reader, bits)
  40. if err != nil {
  41. panic(err)
  42. }
  43. //保存私钥
  44. //通过x509标准将得到的ras私钥序列化为ASN.1 的 DER编码字符串
  45. X509PrivateKey := x509.MarshalPKCS1PrivateKey(privateKey)
  46. //使用pem格式对x509输出的内容进行编码
  47. //创建文件保存私钥
  48. privateFile, err := os.Create(SysConfigDir + "private.pem")
  49. if err != nil {
  50. panic(err)
  51. }
  52. defer privateFile.Close()
  53. //构建一个pem.Block结构体对象
  54. privateBlock := pem.Block{Type: "RSA Private Key", Bytes: X509PrivateKey}
  55. //将数据保存到文件
  56. pem.Encode(privateFile, &privateBlock)
  57. //保存公钥
  58. //获取公钥的数据
  59. publicKey := privateKey.PublicKey
  60. //X509对公钥编码
  61. X509PublicKey, err := x509.MarshalPKIXPublicKey(&publicKey)
  62. if err != nil {
  63. panic(err)
  64. }
  65. //pem格式编码
  66. //创建用于保存公钥的文件
  67. publicFile, err := os.Create(SysConfigDir + "public.pem")
  68. if err != nil {
  69. panic(err)
  70. }
  71. defer publicFile.Close()
  72. //创建一个pem.Block结构体对象
  73. publicBlock := pem.Block{Type: "RSA Public Key", Bytes: X509PublicKey}
  74. //保存到文件
  75. pem.Encode(publicFile, &publicBlock)
  76. }
  77. func RSA_DecryptLong(cipherText []byte, paths ...string) ([]byte, error) {
  78. path := SysConfigDir + "private.pem"
  79. if len(paths) > 0 {
  80. path = paths[0]
  81. }
  82. //打开文件
  83. file, err := os.Open(path)
  84. if err != nil {
  85. return nil, err
  86. }
  87. defer file.Close()
  88. //获取文件内容
  89. info, err := file.Stat()
  90. if err != nil {
  91. return nil, err
  92. }
  93. buf := make([]byte, info.Size())
  94. file.Read(buf)
  95. //pem解码
  96. block, _ := pem.Decode(buf)
  97. //X509解码
  98. priKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
  99. if err != nil {
  100. return nil, err
  101. }
  102. path2 := SysConfigDir + "public.pem"
  103. if len(paths) > 0 {
  104. path2 = paths[0]
  105. }
  106. //打开文件
  107. file2, err := os.Open(path2)
  108. if err != nil {
  109. panic(err)
  110. }
  111. defer file2.Close()
  112. //读取文件的内容
  113. info2, _ := file2.Stat()
  114. buf2 := make([]byte, info2.Size())
  115. file2.Read(buf2)
  116. //pem解码
  117. block2, _ := pem.Decode(buf2)
  118. //x509解码
  119. publicKeyInterface, err := x509.ParsePKIXPublicKey(block2.Bytes)
  120. if err != nil {
  121. panic(err)
  122. }
  123. //类型断言
  124. pubKey := publicKeyInterface.(*rsa.PublicKey)
  125. partLen := pubKey.N.BitLen() / 8
  126. chunks := split(cipherText, partLen)
  127. buffer := bytes.NewBufferString("")
  128. for _, chunk := range chunks {
  129. //对密文进行解密
  130. plainText, err := rsa.DecryptPKCS1v15(rand.Reader, priKey, chunk)
  131. if err != nil {
  132. return nil, err
  133. }
  134. buffer.Write(plainText)
  135. }
  136. //返回明文
  137. return []byte(buffer.String()), nil
  138. }
  139. func split(buf []byte, lim int) [][]byte {
  140. var chunk []byte
  141. chunks := make([][]byte, 0, len(buf)/lim+1)
  142. for len(buf) >= lim {
  143. chunk, buf = buf[:lim], buf[lim:]
  144. chunks = append(chunks, chunk)
  145. }
  146. if len(buf) > 0 {
  147. chunks = append(chunks, buf[:len(buf)])
  148. }
  149. return chunks
  150. }
  151. // RSA_Encrypt
  152. // @Description: RSA加密,当前端传过来时需要使用
  153. // @param plainText
  154. // @param path
  155. // @return []byte
  156. func RSA_Encrypt(plainText []byte, paths ...string) []byte {
  157. path := SysConfigDir + "public.pem"
  158. if len(paths) > 0 {
  159. path = paths[0]
  160. }
  161. //打开文件
  162. file, err := os.Open(path)
  163. if err != nil {
  164. panic(err)
  165. }
  166. defer file.Close()
  167. //读取文件的内容
  168. info, _ := file.Stat()
  169. buf := make([]byte, info.Size())
  170. file.Read(buf)
  171. log.Println(string(buf))
  172. //pem解码
  173. block, _ := pem.Decode(buf)
  174. //x509解码
  175. publicKeyInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
  176. if err != nil {
  177. panic(err)
  178. }
  179. //类型断言
  180. pubKey := publicKeyInterface.(*rsa.PublicKey)
  181. //对明文进行加密
  182. cipherText, err := rsa.EncryptPKCS1v15(rand.Reader, pubKey, plainText)
  183. if err != nil {
  184. panic(err)
  185. }
  186. //返回密文
  187. return cipherText
  188. }
  189. // RSA_Decrypt
  190. // @Description: RSA解密
  191. // @param cipherText
  192. // @param paths
  193. // @return []byte
  194. // @return error
  195. func RSA_Decrypt(cipherText []byte, paths ...string) ([]byte, error) {
  196. path := SysConfigDir + "private.pem"
  197. if len(paths) > 0 {
  198. path = paths[0]
  199. }
  200. //打开文件
  201. file, err := os.Open(path)
  202. if err != nil {
  203. return nil, err
  204. }
  205. defer file.Close()
  206. //获取文件内容
  207. info, err := file.Stat()
  208. if err != nil {
  209. return nil, err
  210. }
  211. buf := make([]byte, info.Size())
  212. file.Read(buf)
  213. //pem解码
  214. block, _ := pem.Decode(buf)
  215. //X509解码
  216. priKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
  217. if err != nil {
  218. return nil, err
  219. }
  220. //对密文进行解密
  221. plainText, err := rsa.DecryptPKCS1v15(rand.Reader, priKey, cipherText)
  222. if err != nil {
  223. return nil, err
  224. }
  225. //返回明文
  226. return plainText, nil
  227. }
  228. // Md5Crypt 加盐MD5加密
  229. // @params str 需要加密的字符串
  230. // @params salt interface{} 加密的盐
  231. // @return str 返回md5码
  232. func Md5Crypt(str string, salt ...interface{}) (CryptStr string) {
  233. if l := len(salt); l > 0 {
  234. slice := make([]string, l+1)
  235. str = fmt.Sprintf(str+strings.Join(slice, "%v"), salt...)
  236. }
  237. return fmt.Sprintf("%x", md5.Sum([]byte(str)))
  238. }
  239. // MD5Bytes 数据块MD5计算函数
  240. func MD5Bytes(s []byte) string {
  241. ret := md5.Sum(s)
  242. return fmt.Sprintf("%x", ret)
  243. }
  244. // MD5 计算字符串MD5值
  245. func MD5(s string) string {
  246. return MD5Bytes([]byte(s))
  247. }
  248. // EncryptDES_CBC CBC加密
  249. func EncryptDES_CBC(src, key string) string {
  250. data := []byte(src)
  251. keyByte := []byte(key)
  252. block, err := des.NewCipher(keyByte)
  253. if err != nil {
  254. panic(err)
  255. }
  256. data = PKCS5Padding(data, block.BlockSize())
  257. //获取CBC加密模式
  258. iv := keyByte //用密钥作为向量(不建议这样使用)
  259. mode := cipher.NewCBCEncrypter(block, iv)
  260. out := make([]byte, len(data))
  261. mode.CryptBlocks(out, data)
  262. return fmt.Sprintf("%X", out)
  263. }
  264. // CBC解密
  265. func DecryptDES_CBC(src, key string) string {
  266. keyByte := []byte(key)
  267. data, err := hex.DecodeString(src)
  268. if err != nil {
  269. panic(err)
  270. }
  271. block, err := des.NewCipher(keyByte)
  272. if err != nil {
  273. panic(err)
  274. }
  275. iv := keyByte //用密钥作为向量(不建议这样使用)
  276. mode := cipher.NewCBCDecrypter(block, iv)
  277. plaintext := make([]byte, len(data))
  278. mode.CryptBlocks(plaintext, data)
  279. plaintext = PKCS5UnPadding(plaintext)
  280. return string(plaintext)
  281. }
  282. // ECB加密
  283. func EncryptDES_ECB(src, key string) string {
  284. data := []byte(src)
  285. keyByte := []byte(key)
  286. block, err := des.NewCipher(keyByte)
  287. if err != nil {
  288. panic(err)
  289. }
  290. bs := block.BlockSize()
  291. //对明文数据进行补码
  292. data = PKCS5Padding(data, bs)
  293. if len(data)%bs != 0 {
  294. panic("Need a multiple of the blocksize")
  295. }
  296. out := make([]byte, len(data))
  297. dst := out
  298. for len(data) > 0 {
  299. //对明文按照blocksize进行分块加密
  300. //必要时可以使用go关键字进行并行加密
  301. block.Encrypt(dst, data[:bs])
  302. data = data[bs:]
  303. dst = dst[bs:]
  304. }
  305. return fmt.Sprintf("%X", out)
  306. }
  307. // ECB解密
  308. func DecryptDES_ECB(src, key string) string {
  309. data, err := hex.DecodeString(src)
  310. if err != nil {
  311. panic(err)
  312. }
  313. keyByte := []byte(key)
  314. block, err := des.NewCipher(keyByte)
  315. if err != nil {
  316. panic(err)
  317. }
  318. bs := block.BlockSize()
  319. if len(data)%bs != 0 {
  320. panic("crypto/cipher: input not full blocks")
  321. }
  322. out := make([]byte, len(data))
  323. dst := out
  324. for len(data) > 0 {
  325. block.Decrypt(dst, data[:bs])
  326. data = data[bs:]
  327. dst = dst[bs:]
  328. }
  329. out = PKCS5UnPadding(out)
  330. return string(out)
  331. }
  332. // 明文补码算法
  333. func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
  334. padding := blockSize - len(ciphertext)%blockSize
  335. padtext := bytes.Repeat([]byte{byte(padding)}, padding)
  336. return append(ciphertext, padtext...)
  337. }
  338. // 明文减码算法
  339. func PKCS5UnPadding(origData []byte) []byte {
  340. length := len(origData)
  341. unpadding := int(origData[length-1])
  342. return origData[:(length - unpadding)]
  343. }
  344. // RsaEncrypt Rsa加密
  345. func RsaEncrypt(origData []byte) ([]byte, error) {
  346. block, _ := pem.Decode(publicKey)
  347. publicKeyInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
  348. if err != nil {
  349. panic(err)
  350. }
  351. //类型断言
  352. pubKey := publicKeyInterface.(*rsa.PublicKey)
  353. encryptedBytes, err := rsa.EncryptPKCS1v15(rand.Reader, pubKey, origData)
  354. return encryptedBytes, err
  355. }
  356. // RsaDecrypt Rsa解密
  357. func RsaDecrypt(cipherText []byte) ([]byte, error) {
  358. //解密
  359. block, _ := pem.Decode(privateKey)
  360. if block == nil {
  361. return nil, errors.New("private key error!")
  362. }
  363. //解析PKCS1格式的私钥
  364. priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
  365. if err != nil {
  366. return nil, err
  367. }
  368. //解密密文
  369. return rsa.DecryptPKCS1v15(rand.Reader, priv, cipherText)
  370. }
  371. func RSADecryptByPrivateKey(data string, privateKey string) (string, error) {
  372. priKey, err := crypto4go.ParsePKCS1PrivateKey(crypto4go.FormatPKCS1PrivateKey(string(privateKey)))
  373. if err != nil {
  374. priKey, err = crypto4go.ParsePKCS8PrivateKey(crypto4go.FormatPKCS8PrivateKey(string(privateKey)))
  375. if err != nil {
  376. fmt.Println("ParsePKCS8PrivateKey : ", err.Error())
  377. return "", err
  378. }
  379. }
  380. // 转成base64
  381. key, err := base64.StdEncoding.DecodeString(data)
  382. if err != nil {
  383. fmt.Println("base64.RawURLEncoding.DecodeString : ", err.Error())
  384. return "", err
  385. }
  386. partLen := priKey.N.BitLen() / 8
  387. chunks := split([]byte(key), partLen)
  388. buffer := bytes.NewBufferString("")
  389. for _, chunk := range chunks {
  390. decrypted, err := rsa.DecryptPKCS1v15(rand.Reader, priKey, chunk)
  391. if err != nil {
  392. return "", err
  393. }
  394. buffer.Write(decrypted)
  395. }
  396. return buffer.String(), err
  397. }