Golang中常见加密算法的总结

如果想直接使用我下列的库

可以直接go get 我的github

go get -u github.com/hybpjx/InverseAlgorithm

1.md5 加密——不可逆

MD5信息摘要算法是一种被广泛使用的密码散列函数,可以产生出一个128位(16进制,32个字符)的散列值(hash value),用于确保信息传输完整一致。

  1. import (
  2.      “crypto/md5”
  3.      “encoding/hex”
  4.      “fmt”
  5. )

第一种

  1. // MD5Str md5验证
  2. func MD5Str(src string) string {
  3.      h := md5.New()
  4.      h.Write([]byte(src)) // 需要加密的字符串为
  5.      fmt.Printf(“%s\n”, hex.EncodeToString(h.Sum(nil))) // 输出加密结果
  6.      return hex.EncodeToString(h.Sum(nil))
  7. }

第二种

  1. // MD5Str2 md5验证
  2. func MD5Str2(src string) string {
  3.      return fmt.Sprintf(“%x”, md5.Sum([]byte(src)))
  4. }

2.hmacsha 加密——不可逆

HMAC是密钥相关的哈希运算消息认证码(Hash-based Message Authentication Code)的缩写,它通过一个标准算法,在计算哈希的过程中,把key混入计算过程中。

和我们自定义的加salt算法不同,Hmac算法针对所有哈希算法都通用,无论是MD5还是SHA-1。采用Hmac替代我们自己的salt算法,可以使程序算法更标准化,也更安全。

hmac-md5加密

  1. //key随意设置 data 要加密数据
  2. func Hmac(key, data string) string {
  3.      // 创建对应的md5哈希加密算法
  4.      hash:= hmac.New(md5.New, []byte(key))
  5.      hash.Write([]byte(data))
  6.      return hex.EncodeToString(hash.Sum([]byte(“”)))
  7. }

hamacsha1 加密

  1. // HmacSha1 hmacSha1加密 key随意设置 data 要加密数据
  2. func HmacSha1(src, key string) string {
  3.      m := hmac.New(sha1.New, []byte(key))
  4.      m.Write([]byte(src))
  5.      return hex.EncodeToString(m.Sum(nil))
  6. }

hamacsha 256 加密

  1. // HmacSHA256 hmacSha256验证 key随意设置 data 要加密数据
  2. func HmacSHA256(key, src string) string {
  3.      m := hmac.New(sha256.New, []byte(key))
  4.      m.Write([]byte(src))
  5.      return hex.EncodeToString(m.Sum(nil))
  6. }

hmacsha512加密

  1. // HmacSHA512 hmacSha512验证
  2. func HmacSHA512(key, src string) string {
  3.      m := hmac.New(sha512.New, []byte(key))
  4.      m.Write([]byte(src))
  5.      return hex.EncodeToString(m.Sum(nil))
  6. }

hamasha 调用

  1. package main
  2. import (
  3.      “crypto/hmac”
  4.      “crypto/md5”
  5.      “crypto/sha1”
  6.      “crypto/sha256”
  7.      “crypto/sha512”
  8.      “encoding/hex”
  9.      “fmt”
  10. )
  11. // Hmac hmac验证 key随意设置 data 要加密数据
  12. func Hmac(key, data string) string {
  13.      hash := hmac.New(md5.New, []byte(key)) // 创建对应的md5哈希加密算法
  14.      hash.Write([]byte(data))
  15.      return hex.EncodeToString(hash.Sum([]byte(“”)))
  16. }
  17. // HmacSHA256 hmacSha256加密 key随意设置 data 要加密数据
  18. func HmacSHA256(key, src string) string {
  19.      m := hmac.New(sha256.New, []byte(key))
  20.      m.Write([]byte(src))
  21.      return hex.EncodeToString(m.Sum(nil))
  22. }
  23. // HmacSHA512 hmacSha512加密 key随意设置 data 要加密数据
  24. func HmacSHA512(key, src string) string {
  25.      m := hmac.New(sha512.New, []byte(key))
  26.      m.Write([]byte(src))
  27.      return hex.EncodeToString(m.Sum(nil))
  28. }
  29. // HmacSha1 hmacSha1加密 key随意设置 data 要加密数据
  30. func HmacSha1(src, key string) string {
  31.      m := hmac.New(sha1.New, []byte(key))
  32.      m.Write([]byte(src))
  33.      return hex.EncodeToString(m.Sum(nil))
  34. }
  35. // SHA256Str sha256加密
  36. func SHA256Str(src string) string {
  37.      h := sha256.New()
  38.      h.Write([]byte(src)) // 需要加密的字符串为
  39.      // fmt.Printf(“%s\n”, hex.EncodeToString(h.Sum(nil))) // 输出加密结果
  40.      return hex.EncodeToString(h.Sum(nil))
  41. }
  42. func main() {
  43.      hmac_ := Hmac(“hybpjx”, “始識”)
  44.      hamcsha1 := HmacSha1(“hybpjx”, “始識”)
  45.      hamcsha256 := HmacSHA256(“hybpjx”, “始識”)
  46.      hamacsha512 := HmacSHA512(“hybpjx”, “始識”)
  47.      fmt.Println(hmac_)
  48.      fmt.Println(hamcsha1)
  49.      fmt.Println(hamcsha256)
  50.      fmt.Println(hamacsha512)
  51. }

结果

d8801f70df7891764116e1ac003f7189
60d68e01c8a86f3b87e4e147e9f0fadce2a69661
b3f8ddf991288036864761a55046877adfe4f78ec9a89bb63932af92689b139f
b9b1fca0fe91522482ee1b2161e57d67482af6ef371614365b918c31ce774f9126ed627e378a063145f404ff2de7bd84f8e4798c385662ef4749e58e9209ca63

3.Sha 加密——不可逆

sha1

SHA-1可以生成一个被称为消息摘要的160位(20字节)散列值,散列值通常的呈现形式为40个十六进制数。

  1. func Sha1(data string) string {
  2.      sha1_ := sha1.New()
  3.      sha1_.Write([]byte(data))
  4.      return hex.EncodeToString(sha1_.Sum([]byte(“”)))
  5. }

sha256

SHA256算法使用的哈希值长度是256位。这是一个抽象类。此类的唯一实现是SHA256Managed。

  1. // SHA256 sha256加密
  2. func SHA256(src string) string {
  3.      h := sha256.New()
  4.      // 需要加密的字符串为
  5.      h.Write([]byte(src))
  6.      // fmt.Printf(“%s\n”, hex.EncodeToString(h.Sum(nil))) // 输出加密结果
  7.      return hex.EncodeToString(h.Sum(nil))
  8. }

sha512

SHA (Secure Hash Algorithm,译作安全散列算法) 是美国国家安全局 (NSA) 设计,美国国家标准与技术研究院 (NIST) 发布的一系列密码散列函数。

  1. // SHA512 sha512加密
  2. func SHA512(src string) string {
  3.      h := sha512.New()
  4.      // 需要加密的字符串为
  5.      h.Write([]byte(src))
  6.      // fmt.Printf(“%s\n”, hex.EncodeToString(h.Sum(nil))) // 输出加密结果
  7.      return hex.EncodeToString(h.Sum(nil))
  8. }

sha调用

  1. package main
  2. import (
  3.      “crypto/sha1”
  4.      “crypto/sha256”
  5.      “crypto/sha512”
  6.      “encoding/hex”
  7.      “fmt”
  8. )
  9. func Sha1(data string) string {
  10.      sha1_ := sha1.New()
  11.      sha1_.Write([]byte(data))
  12.      return hex.EncodeToString(sha1_.Sum([]byte(“”)))
  13. }
  14. // SHA256 sha256加密
  15. func SHA256(src string) string {
  16.      h := sha256.New()
  17.      // 需要加密的字符串为
  18.      h.Write([]byte(src))
  19.      // fmt.Printf(“%s\n”, hex.EncodeToString(h.Sum(nil))) // 输出加密结果
  20.      return hex.EncodeToString(h.Sum(nil))
  21. }
  22. // SHA512 sha512加密
  23. func SHA512(src string) string {
  24.      h := sha512.New()
  25.      // 需要加密的字符串为
  26.      h.Write([]byte(src))
  27.      // fmt.Printf(“%s\n”, hex.EncodeToString(h.Sum(nil))) // 输出加密结果
  28.      return hex.EncodeToString(h.Sum(nil))
  29. }
  30. func main() {
  31.      _sha1 := Sha1(“始識”)
  32.      _sha256 := SHA256(“始識”)
  33.      _sha512 := SHA512(“始識”)
  34.      fmt.Println(_sha1)
  35.      fmt.Println(_sha256)
  36.      fmt.Println(_sha512)
  37. }

结果

7bac01cc58a26f3cb280b0466794a89441279946
6ef99e6d3fe34a46afcdc438435728fe95ffdab18e389ddd31609edd6729b11d
0c04e9b79f488646d0eac6f65468248507939d643cc92709b14eb0d18d8f13db509ed5ccd3312d6c234408185a4611a42525dce9e8d32255640f56a2f836635a

4.base 加密 解密

加密

  1. // BASE64StdEncode base编码
  2. func BASE64StdEncode(src string) string {
  3.      return base64.StdEncoding.EncodeToString([]byte(src))
  4. }

解密

  1. // BASE64StdDecode base解码
  2. func BASE64StdDecode(src string) string {
  3.      a, err := base64.StdEncoding.DecodeString(src)
  4.      if err != nil {
  5.          _ = fmt.Errorf(“解密失败,%v\n”, err)
  6.      }
  7.      return string(a)
  8. }

base64 调用

  1. package main
  2. import (
  3.      “encoding/base64”
  4.      “fmt”
  5. )
  6. // BASE64StdEncode base编码
  7. func BASE64StdEncode(src string) string {
  8.      return base64.StdEncoding.EncodeToString([]byte(src))
  9. }
  10. // BASE64StdDecode base解码
  11. func BASE64StdDecode(src string) string {
  12.      a, err := base64.StdEncoding.DecodeString(src)
  13.      if err != nil {
  14.          _ = fmt.Errorf(“解密失败,%v\n”, err)
  15.      }
  16.      return string(a)
  17. }
  18. func main() {
  19.      encodeBase64 := BASE64StdEncode(“hybpjx”)
  20.      decodeBase64 := BASE64StdDecode(encodeBase64)
  21.      fmt.Println(encodeBase64)
  22.      fmt.Println(decodeBase64)
  23. }

结果

aHlicGp4
hybpjx

5.AES 加密

高级加密标准(英语:Advanced Encryption Standard,缩写:AES),在密码学中又称Rijndael加密法。这个标准用来替代原先的DES,已经被多方分析且广为全世界所使用。经过五年的甄选流程,于2001年11月26日发布于FIPS PUB 197,并在2002年5月26日成为有效的标准。2006年,高级加密标准已然成为对称密钥加密中最流行的算法之一。

由于加密和解密的秘钥是相同的,所以AES为对称加密

  1. package main
  2. import (
  3.      “bytes”
  4.      “crypto/aes”
  5.      “crypto/cipher”
  6.      “encoding/base64”
  7.      “fmt”
  8. )
  9. func PKCS7Padding(ciphertext []byte, blockSize int) []byte {
  10.      padding := blockSize  len(ciphertext)%blockSize
  11.      padtext := bytes.Repeat([]byte{byte(padding)}, padding)
  12.      return append(ciphertext, padtext…)
  13. }
  14. func PKCS7UnPadding(origData []byte) []byte {
  15.      length := len(origData)
  16.      unpadding := int(origData[length1])
  17.      return origData[:(length  unpadding)]
  18. }
  19. //AES加密
  20. func AesEncrypt(origData, key []byte) ([]byte, error) {
  21.      block, err := aes.NewCipher(key)
  22.      if err != nil {
  23.          return nil, err
  24.      }
  25.      blockSize := block.BlockSize()
  26.      origData = PKCS7Padding(origData, blockSize)
  27.      blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
  28.      crypted := make([]byte, len(origData))
  29.      blockMode.CryptBlocks(crypted, origData)
  30.      return crypted, nil
  31. }
  32. //AES解密
  33. func AesDecrypt(crypted, key []byte) ([]byte, error) {
  34.      block, err := aes.NewCipher(key)
  35.      if err != nil {
  36.          return nil, err
  37.      }
  38.      blockSize := block.BlockSize()
  39.      blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
  40.      origData := make([]byte, len(crypted))
  41.      blockMode.CryptBlocks(origData, crypted)
  42.      origData = PKCS7UnPadding(origData)
  43.      return origData, nil
  44. }
  45. func main() {
  46.      text := “今晚打老虎”
  47.      AesKey := []byte(“0f90023fc9ae101e”) //秘钥长度为16的倍数
  48.      fmt.Printf(“明文: %s\n秘钥: %s\n”, text, string(AesKey))
  49.      encrypted, err := AesEncrypt([]byte(text), AesKey)
  50.      if err != nil {
  51.          panic(err)
  52.      }
  53.      fmt.Printf(“加密后: %s\n”, base64.StdEncoding.EncodeToString(encrypted))
  54.      origin, err := AesDecrypt(encrypted, AesKey)
  55.      if err != nil {
  56.          panic(err)
  57.      }
  58.      fmt.Printf(“解密后明文: %s\n”, string(origin))
  59. }

CBC方式

  1. package main
  2. import (
  3.      “bytes”
  4.      “crypto/aes”
  5.      “crypto/cipher”
  6.      “encoding/base64”
  7.      “encoding/hex”
  8.      “log”
  9. )
  10. func AesEncryptCBC(origData []byte, key []byte) (encrypted []byte) {
  11.      // 分组秘钥
  12.      // NewCipher该函数限制了输入k的长度必须为16, 24或者32
  13.      block, _ := aes.NewCipher(key)
  14.      blockSize := block.BlockSize() // 获取秘钥块的长度
  15.      origData = pkcs5Padding(origData, blockSize) // 补全码
  16.      blockMode := cipher.NewCBCEncrypter(block, key[:blockSize]) // 加密模式
  17.      encrypted = make([]byte, len(origData)) // 创建数组
  18.      blockMode.CryptBlocks(encrypted, origData) // 加密
  19.      return encrypted
  20. }
  21. func AesDecryptCBC(encrypted []byte, key []byte) (decrypted []byte) {
  22.      block, _ := aes.NewCipher(key) // 分组秘钥
  23.      blockSize := block.BlockSize() // 获取秘钥块的长度
  24.      blockMode := cipher.NewCBCDecrypter(block, key[:blockSize]) // 加密模式
  25.      decrypted = make([]byte, len(encrypted)) // 创建数组
  26.      blockMode.CryptBlocks(decrypted, encrypted) // 解密
  27.      decrypted = pkcs5UnPadding(decrypted) // 去除补全码
  28.      return decrypted
  29. }
  30. func pkcs5Padding(ciphertext []byte, blockSize int) []byte {
  31.      padding := blockSize  len(ciphertext)%blockSize
  32.      padtext := bytes.Repeat([]byte{byte(padding)}, padding)
  33.      return append(ciphertext, padtext…)
  34. }
  35. func pkcs5UnPadding(origData []byte) []byte {
  36.      length := len(origData)
  37.      unpadding := int(origData[length1])
  38.      return origData[:(length  unpadding)]
  39. }
  40. func main() {
  41.      origData := []byte(“460154561234”) // 待加密的数据
  42.      key := []byte(“9876787656785679”) // 加密的密钥
  43.      log.Println(“原文:”, string(origData))
  44.      log.Println(“—————— CBC模式 ——————–“)
  45.      encrypted := AesEncryptCBC(origData, key)
  46.      log.Println(“密文(hex):”, hex.EncodeToString(encrypted))
  47.      log.Println(“密文(base64):”, base64.StdEncoding.EncodeToString(encrypted))
  48.      decrypted := AesDecryptCBC(encrypted, key)
  49.      log.Println(“解密结果:”, string(decrypted))
  50. }

ECB方式

  1. package main
  2. import (
  3.      “crypto/aes”
  4.      “encoding/base64”
  5.      “encoding/hex”
  6.      “log”
  7. )
  8. func AesEncryptECB(origData []byte, key []byte) (encrypted []byte) {
  9.      cipher, _ := aes.NewCipher(generateKey(key))
  10.      length := (len(origData) + aes.BlockSize) / aes.BlockSize
  11.      plain := make([]byte, length*aes.BlockSize)
  12.      copy(plain, origData)
  13.      pad := byte(len(plain)  len(origData))
  14.      for i := len(origData); i < len(plain); i++ {
  15.          plain[i] = pad
  16.      }
  17.      encrypted = make([]byte, len(plain))
  18.      // 分组分块加密
  19.      for bs, be := 0, cipher.BlockSize(); bs <= len(origData); bs, be = bs+cipher.BlockSize(), be+cipher.BlockSize() {
  20.          cipher.Encrypt(encrypted[bs:be], plain[bs:be])
  21.      }
  22.      return encrypted
  23. }
  24. func AesDecryptECB(encrypted []byte, key []byte) (decrypted []byte) {
  25.      cipher, _ := aes.NewCipher(generateKey(key))
  26.      decrypted = make([]byte, len(encrypted))
  27.      //
  28.      for bs, be := 0, cipher.BlockSize(); bs < len(encrypted); bs, be = bs+cipher.BlockSize(), be+cipher.BlockSize() {
  29.          cipher.Decrypt(decrypted[bs:be], encrypted[bs:be])
  30.      }
  31.      trim := 0
  32.      if len(decrypted) > 0 {
  33.          trim = len(decrypted)  int(decrypted[len(decrypted)-1])
  34.      }
  35.      return decrypted[:trim]
  36. }
  37. func generateKey(key []byte) (genKey []byte) {
  38.      genKey = make([]byte, 16)
  39.      copy(genKey, key)
  40.      for i := 16; i < len(key); {
  41.          for j := 0; j < 16 && i < len(key); j, i = j+1, i+1 {
  42.              genKey[j] ^= key[i]
  43.          }
  44.      }
  45.      return genKey
  46. }
  47. func main() {
  48.      origData := []byte(“460154561234”) // 待加密的数据
  49.      key := []byte(“9876787656785679”) // 加密的密钥
  50.      log.Println(“原文:”, string(origData))
  51.      log.Println(“—————— ECB模式 ——————–“)
  52.      encrypted := AesEncryptECB(origData, key)
  53.      log.Println(“密文(hex):”, hex.EncodeToString(encrypted))
  54.      log.Println(“密文(base64):”, base64.StdEncoding.EncodeToString(encrypted))
  55.      decrypted := AesDecryptECB(encrypted, key)
  56.      log.Println(“解密结果:”, string(decrypted))
  57. }

CFB 方式

  1. package main
  2. import (
  3.      “crypto/aes”
  4.      “crypto/cipher”
  5.      “crypto/rand”
  6.      “encoding/base64”
  7.      “encoding/hex”
  8.      “io”
  9.      “log”
  10. )
  11. func AesEncryptCFB(origData []byte, key []byte) (encrypted []byte) {
  12.      block, err := aes.NewCipher(key)
  13.      if err != nil {
  14.          panic(err)
  15.      }
  16.      encrypted = make([]byte, aes.BlockSize+len(origData))
  17.      iv := encrypted[:aes.BlockSize]
  18.      if _, err := io.ReadFull(rand.Reader, iv); err != nil {
  19.          panic(err)
  20.      }
  21.      stream := cipher.NewCFBEncrypter(block, iv)
  22.      stream.XORKeyStream(encrypted[aes.BlockSize:], origData)
  23.      return encrypted
  24. }
  25. func AesDecryptCFB(encrypted []byte, key []byte) (decrypted []byte) {
  26.      block, _ := aes.NewCipher(key)
  27.      if len(encrypted) < aes.BlockSize {
  28.          panic(“ciphertext too short”)
  29.      }
  30.      iv := encrypted[:aes.BlockSize]
  31.      encrypted = encrypted[aes.BlockSize:]
  32.      stream := cipher.NewCFBDecrypter(block, iv)
  33.      stream.XORKeyStream(encrypted, encrypted)
  34.      return encrypted
  35. }
  36. func main() {
  37.      origData := []byte(“460154561234”) // 待加密的数据
  38.      key := []byte(“9876787656785679”) // 加密的密钥
  39.      log.Println(“原文:”, string(origData))
  40.      log.Println(“—————— CFB模式 ——————–“)
  41.      encrypted := AesEncryptCFB(origData, key)
  42.      log.Println(“密文(hex):”, hex.EncodeToString(encrypted))
  43.      log.Println(“密文(base64):”, base64.StdEncoding.EncodeToString(encrypted))
  44.      decrypted := AesDecryptCFB(encrypted, key)
  45.      log.Println(“解密结果:”, string(decrypted))
  46. }

6.RSA加密

RSA是一种基于公钥密码体制的优秀加密算法,1978年由美国(MIT)的李维斯特(Rivest)、沙米尔(Shamir)、艾德曼(Adleman)提的。

RSA算法是一种分组密码体制算法,它的保密强度是建立在具有大素数因子的合数其因子分解是困难的(基于大数分解的难度)。公钥和私钥是一对大素数的函数,从一个公钥和密文中恢复出明文的难度等价于分解两个大素数之积。

RSA得到了世界上的最广泛的应用,ISO在1992年颁布的国际标准X.509中,将RSA算法正式纳入国际标准。

RSA加密

  1. package main
  2. import (
  3.      “crypto/rand”
  4.      “crypto/rsa”
  5.      “crypto/x509”
  6.      “encoding/pem”
  7.      “fmt”
  8.      “os”
  9. )
  10. // GenerateRSAKey 生成RSA私钥和公钥,保存到文件中
  11. func GenerateRSAKey(bits int){
  12.      //GenerateKey函数使用随机数据生成器random生成一对具有指定字位数的RSA密钥
  13.      //Reader是一个全局、共享的密码用强随机数生成器
  14.      privateKey, err := rsa.GenerateKey(rand.Reader, bits)
  15.      if err!=nil{
  16.          panic(err)
  17.      }
  18.      //保存私钥
  19.      //通过x509标准将得到的ras私钥序列化为ASN.1 的 DER编码字符串
  20.      // X509PrivateKey := x509.MarshalPKCS1PrivateKey(privateKey) // PKCS1 和 9 是不一致的
  21.      X509PrivateKey,err := x509.MarshalPKCS8PrivateKey(privateKey)
  22.      if err != nil {
  23.          fmt.Println(err.Error())
  24.          os.Exit(0)
  25.      }
  26.      //使用pem格式对x509输出的内容进行编码
  27.      //创建文件保存私钥
  28.      privateFile, err := os.Create(“private.pem”)
  29.      if err!=nil{
  30.          panic(err)
  31.      }
  32.      defer privateFile.Close()
  33.      //构建一个pem.Block结构体对象
  34.      privateBlock:= pem.Block{Type: “PRIVATE KEY”,Bytes:X509PrivateKey}
  35.      //将数据保存到文件
  36.      pem.Encode(privateFile,&privateBlock)
  37.      //保存公钥
  38.      //获取公钥的数据
  39.      publicKey:=privateKey.PublicKey
  40.      //X509对公钥编码
  41.      X509PublicKey,err:=x509.MarshalPKIXPublicKey(&publicKey)
  42.      if err!=nil{
  43.          panic(err)
  44.      }
  45.      //pem格式编码
  46.      //创建用于保存公钥的文件
  47.      publicFile, err := os.Create(“public.pem”)
  48.      if err!=nil{
  49.          panic(err)
  50.      }
  51.      defer publicFile.Close()
  52.      //创建一个pem.Block结构体对象
  53.      publicBlock:= pem.Block{Type: “Public Key”,Bytes:X509PublicKey}
  54.      //保存到文件
  55.      pem.Encode(publicFile,&publicBlock)
  56. }
  57. // RsaEncrypt RSA加密
  58. func RsaEncrypt(plainText []byte,path string)[]byte{
  59.      //打开文件
  60.      file,err:=os.Open(path)
  61.      if err!=nil{
  62.          panic(err)
  63.      }
  64.      defer file.Close()
  65.      //读取文件的内容
  66.      info, _ := file.Stat()
  67.      buf:=make([]byte,info.Size())
  68.      file.Read(buf)
  69.      //pem解码
  70.      block, _ := pem.Decode(buf)
  71.      //x509解码
  72.      publicKeyInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
  73.      if err!=nil{
  74.          panic(err)
  75.      }
  76.      //类型断言
  77.      publicKey:=publicKeyInterface.(*rsa.PublicKey)
  78.      //对明文进行加密
  79.      cipherText, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey, plainText)
  80.      if err!=nil{
  81.          panic(err)
  82.      }
  83.      //返回密文
  84.      return cipherText
  85. }
  86. // RsaDecrypt RSA解密
  87. func RsaDecrypt(cipherText []byte,path string) []byte{
  88.      //打开文件
  89.      file,err:=os.Open(path)
  90.      if err!=nil{
  91.          panic(err)
  92.      }
  93.      defer file.Close()
  94.      //获取文件内容
  95.      info, _ := file.Stat()
  96.      buf:=make([]byte,info.Size())
  97.      file.Read(buf)
  98.      //pem解码
  99.      block, _ := pem.Decode(buf)
  100.      //X509解码
  101.      privateKey, err := x509.ParsePKCS8PrivateKey(block.Bytes)
  102.      if err!=nil{
  103.          fmt.Println(err.Error())
  104.          os.Exit(0)
  105.      }
  106.      //对密文进行解密
  107.      plainText,_:=rsa.DecryptPKCS1v15(rand.Reader,privateKey.(*rsa.PrivateKey),cipherText)
  108.      //返回明文
  109.      return plainText
  110. }
  111. func main(){
  112.      // RSA/ECB/PKCS1Padding
  113.      // RSA是算法,ECB是分块模式,PKCS1Padding是填充模式
  114.      // pkcs1私钥生成openssl genrsa -out pkcs1.pem 1024
  115.      // pkcs1转pkcs8私钥 :openssl pkcs8 -in pkcs8.pem -nocrypt -out pkcs1.pem
  116.      // pkcs1 BEGIN RSA PRIVATE KEY
  117.      // pkcs8 BEGIN PRIVATE KEY
  118.      GenerateRSAKey(1024)
  119.      publicPath := “public_key.pem”
  120.      privatePath := “private_key.pem”
  121.      publicPath = “public.pem”
  122.      privatePath = “private.pem”
  123.      txt := []byte(“hello”)
  124.      encrptTxt := RsaEncrypt(txt,publicPath)
  125.      decrptCode := RsaDecrypt(encrptTxt,privatePath)
  126.      fmt.Println(string(decrptCode))
  127. }

RSA分段加密

  1. package main
  2. import (
  3.      “bytes”
  4.      “crypto/rand”
  5.      “crypto/rsa”
  6.      “crypto/x509”
  7.      “encoding/base64”
  8.      “encoding/pem”
  9.      “fmt”
  10.      “log”
  11.      “os”
  12. )
  13. func main() {
  14.      GenerateRSAKey(2048)
  15.      publicPath := “public.pem”
  16.      privatePath := “private.pem”
  17.      var a = []byte(“hello”)
  18.      encrptTxt, err := RsaEncryptBlock(a, publicPath)
  19.      if err != nil {
  20.          fmt.Println(err.Error())
  21.      }
  22.      encodeString := base64.StdEncoding.EncodeToString(encrptTxt)
  23.      decodeByte, err := base64.StdEncoding.DecodeString(encodeString)
  24.      if err != nil {
  25.          panic(err)
  26.      }
  27.      //生成RSA私钥和公钥,保存到文件中
  28.      decrptCode := RSA_Decrypts(decodeByte, privatePath)
  29.      fmt.Println(string(decrptCode))
  30. }
  31. func GenerateRSAKey(bits int) {
  32.      //GenerateKey函数使用随机数据生成器random生成一对具有指定字位数的RSA密钥
  33.      //Reader是一个全局、共享的密码用强随机数生成器
  34.      privateKey, err := rsa.GenerateKey(rand.Reader, bits)
  35.      if err != nil {
  36.          panic(err)
  37.      }
  38.      //保存私钥
  39.      //通过x509标准将得到的ras私钥序列化为ASN.1 的 DER编码字符串
  40.      // X509PrivateKey := x509.MarshalPKCS1PrivateKey(privateKey) // PKCS1 和 9 是不一致的
  41.      X509PrivateKey, err := x509.MarshalPKCS8PrivateKey(privateKey)
  42.      if err != nil {
  43.          fmt.Println(err.Error())
  44.          os.Exit(0)
  45.      }
  46.      //使用pem格式对x509输出的内容进行编码
  47.      //创建文件保存私钥
  48.      privateFile, err := os.Create(“private.pem”)
  49.      if err != nil {
  50.          panic(err)
  51.      }
  52.      defer privateFile.Close()
  53.      //构建一个pem.Block结构体对象
  54.      privateBlock := pem.Block{Type: “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(“public.pem”)
  68.      if err != nil {
  69.          panic(err)
  70.      }
  71.      defer publicFile.Close()
  72.      //创建一个pem.Block结构体对象
  73.      publicBlock := pem.Block{Type: “Public Key”, Bytes: X509PublicKey}
  74.      //保存到文件
  75.      pem.Encode(publicFile, &publicBlock)
  76. }
  77. // RSA_Decrypts RSA解密支持分段解密
  78. func RSA_Decrypts(cipherText []byte, path string) []byte {
  79.      //打开文件
  80.      var bytesDecrypt []byte
  81.      file, err := os.Open(path)
  82.      if err != nil {
  83.          panic(err)
  84.      }
  85.      defer file.Close()
  86.      //获取文件内容
  87.      info, _ := file.Stat()
  88.      buf := make([]byte, info.Size())
  89.      file.Read(buf)
  90.      //pem解码
  91.      block, _ := pem.Decode(buf)
  92.      //X509解码
  93.      privateKey, err := x509.ParsePKCS8PrivateKey(block.Bytes)
  94.      if err != nil {
  95.          fmt.Println(err.Error())
  96.          os.Exit(0)
  97.      }
  98.      p := privateKey.(*rsa.PrivateKey)
  99.      keySize := p.Size()
  100.      srcSize := len(cipherText)
  101.      log.Println(“密钥长度”, keySize, “密文长度”, srcSize)
  102.      var offSet = 0
  103.      var buffer = bytes.Buffer{}
  104.      for offSet < srcSize {
  105.          endIndex := offSet + keySize
  106.          if endIndex > srcSize {
  107.              endIndex = srcSize
  108.          }
  109.          bytesOnce, err := rsa.DecryptPKCS1v15(rand.Reader, p, cipherText[offSet:endIndex])
  110.          if err != nil {
  111.              return nil
  112.          }
  113.          buffer.Write(bytesOnce)
  114.          offSet = endIndex
  115.      }
  116.      bytesDecrypt = buffer.Bytes()
  117.      return bytesDecrypt
  118. }
  119. // RsaEncryptBlock 公钥加密-分段
  120. func RsaEncryptBlock(src []byte, path string) (bytesEncrypt []byte, err error) {
  121.      //打开文件
  122.      file, err := os.Open(path)
  123.      if err != nil {
  124.          panic(err)
  125.      }
  126.      defer file.Close()
  127.      //读取文件的内容
  128.      info, _ := file.Stat()
  129.      buf := make([]byte, info.Size())
  130.      file.Read(buf)
  131.      //pem解码
  132.      block, _ := pem.Decode(buf)
  133.      //x509解码
  134.      publicKeyInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
  135.      if err != nil {
  136.          panic(err)
  137.      }
  138.      //类型断言
  139.      publicKey := publicKeyInterface.(*rsa.PublicKey)
  140.      keySize, srcSize := publicKey.Size(), len(src)
  141.      log.Println(“密钥长度”, keySize, “明文长度”, srcSize)
  142.      offSet, once := 0, keySize11
  143.      buffer := bytes.Buffer{}
  144.      for offSet < srcSize {
  145.          endIndex := offSet + once
  146.          if endIndex > srcSize {
  147.              endIndex = srcSize
  148.          }
  149.          // 加密一部分
  150.          bytesOnce, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey, src[offSet:endIndex])
  151.          if err != nil {
  152.              return nil, err
  153.          }
  154.          buffer.Write(bytesOnce)
  155.          offSet = endIndex
  156.      }
  157.      bytesEncrypt = buffer.Bytes()
  158.      return
  159. }

7.DES加密

DES(Data Encryption)是1977年美国联邦信息处理标准(FIPS)中所采用的一种对称密码(FIPS46-3)。随着计算机的进步,DES已经能够被暴力破解,1997年的DES Challenge I 中用了96天破译密钥,1998年的DES Challenge II-1中用了41天,1998年的DES Challenge II-2中用了56小时,1999年的DES Challenge III 中只用了22小时15分钟。

DES是一种将64比特的明文加密成64比特的密文的对称密码算法,它的密钥的长度是56比特。尽管从规格上来说,DES的密钥长度是64比特,但由于每隔7比特会设置一个用于错误检查的比特,因此实质上其密钥长度是56比特。

DES 是以64比特的明文(比特序列)为一个单位来进行加密的,这个64比特的单位称为分组 ,一般来说,以分组为单位进行处理的密码算法称为分组密码,DES就是分组密码的一种。

DES每次只能加密64比特的数据,如果要加密的明文比较长,就需要对DES加密进行迭代(反复),而迭代的具体方式就称为模式。

DES 内部实现理论:在 des 中各个步骤称为轮,整个加密过程进行16轮循环。

内置库完成

加密模式采用ECB、填充方式采用pkcs5padding、密码使用”12345678″,输出时经hex编码。自己可以通过一些在线测试工具进行测试,看结果是否一致。

  1. package main
  2. import (
  3.      “bytes”
  4.      “crypto/cipher”
  5.      “crypto/des”
  6.      “encoding/hex”
  7.      “fmt”
  8. )
  9. func main() {
  10.      data := []byte(“hello world”)
  11.      key := []byte(“12345678”)
  12.      iv := []byte(“43218765”)
  13.      result, err := DesCBCEncrypt(data, key, iv)
  14.      if err != nil {
  15.          fmt.Println(err)
  16.      }
  17.      b := hex.EncodeToString(result)
  18.      fmt.Println(b)
  19. }
  20. func DesCBCEncrypt(data, key, iv []byte) ([]byte, error) {
  21.      block, err := des.NewCipher(key)
  22.      if err != nil {
  23.          return nil, err
  24.      }
  25.      data = pkcs5Padding(data, block.BlockSize())
  26.      cryptText := make([]byte, len(data))
  27.      blockMode := cipher.NewCBCEncrypter(block, iv)
  28.      blockMode.CryptBlocks(cryptText, data)
  29.      return cryptText, nil
  30. }
  31. func pkcs5Padding(cipherText []byte, blockSize int) []byte {
  32.      padding := blockSize  len(cipherText)%blockSize
  33.      padText := bytes.Repeat([]byte{byte(padding)}, padding)
  34.      return append(cipherText, padText…)
  35. }

使用第三方库

  1. package main
  2. import (
  3.      “fmt”
  4.      “github.com/marspere/goencrypt”
  5. )
  6. func main() {
  7.      // key为12345678
  8.      // iv为空
  9.      // 采用ECB分组模式
  10.      // 采用pkcs5padding填充模式
  11.      // 输出结果使用base64进行加密
  12.      cipher := goencrypt.NewDESCipher([]byte(“12345678”), []byte(“”), goencrypt.ECBMode, goencrypt.Pkcs7, goencrypt.PrintBase64)
  13.      cipherText, err := cipher.DESEncrypt([]byte(“hello world”))
  14.      if err != nil {
  15.          fmt.Println(err)
  16.          return
  17.      }
  18.      fmt.Println(cipherText)
  19. }

8.3DES加密算法

3DES(或称为Triple DES)是三重数据加密算法(TDEA,Triple Data Encryption Algorithm)块密码的通称。它相当于是对每个数据块应用三次DES加密算法。
由于计算机运算能力的增强,原版DES密码的密钥长度变得容易被暴力破解;3DES即是设计用来提供一种相对简单的方法,即通过增加DES的密钥长度来避免类似的攻击,而不是设计一种全新的块密码算法。

还有一个库 非常NB

ECB模式下的3DES算法加解密信息,golang默认只提供CBC模式

这边有golang的加密库,非常厉害

github.com/forgoer/openssl

安装:

go get github.com/thinkoner/openssl

代码如下:

  1. package main
  2. import (
  3.      “encoding/base64”
  4.      “encoding/hex”
  5.      “fmt”
  6.      “github.com/forgoer/openssl”
  7. )
  8. func main() {
  9.      //定义密钥,必须是24byte
  10.      key := []byte(“123456789012345678901234”)
  11.      fmt.Println(“密钥:”, key, hex.EncodeToString(key))
  12.      //定义明文
  13.      src := []byte(“0102030109000000030000000F8898E37A7F8F3D742006111118080000FACE05”)
  14.      //3DES-ECB加密
  15.      encodeData, _ := openssl.Des3ECBEncrypt(src, key, openssl.ZEROS_PADDING)
  16.      encryptBaseData := base64.StdEncoding.EncodeToString(encodeData)
  17.      fmt.Println(“加密后Base64:”, encryptBaseData)
  18.      fmt.Println(“加密后Hex:”, hex.EncodeToString(encodeData))
  19.      //3DES-ECB解密
  20.      decodeBaseData, _ := base64.StdEncoding.DecodeString(encryptBaseData)
  21.      decodeData, _ := openssl.Des3ECBDecrypt(decodeBaseData, key, openssl.ZEROS_PADDING)
  22.      fmt.Println(“解密后:”, hex.EncodeToString(decodeData))
  23. }

包括 Des的加密解密

以下只举一个例子

  1. srcData := “L0j+JvbeVM0svSpjIwXdE7yTu78wiEszCmW8rwjXY3vrx2nEaUeJ/Rw/c/IRdlxIH+/ro4pykx6ESOkGU1YwM8ddEuuoTg5uPsqQ9/SuNds=”
  2. key := []byte(“Ctpsp@884*”[:8])
  3. //3DES-ECB解密
  4. decodeBaseData, _ := base64.StdEncoding.DecodeString(srcData)
  5. decodeData, _ := openssl.DesECBDecrypt(decodeBaseData, key, openssl.PKCS5_PADDING)
  6. fmt.Println(“解密后:”, string(decodeData))

源文件: https://github.com/hybpjx/InverseAlgorithm

以上就是Golang中常见加密算法的总结的详细内容,更多关于Golang加密的资料请关注我们其它相关文章!

标签

发表评论