DEV Community

柯良陈
柯良陈

Posted on

golang encrypt

package main

import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/md5"
"crypto/sha256"
"encoding/base64"
"fmt"
"io"
)

/*

There are three encryption algorithms, RSA AES SHA. but there are not same logic. there are three different encrypted logic.
1.symmetrical encryption
like AES
2.asymmetric encryption
like rsa
3.Data fingerprint
like md5 sha

golang provide go-crypto package to do this.
"crypto/aes"
"crypto/rsa"
"crypto/sha"
"crypto/md5"

*/

func AesEncrypt(orig string, key string) string {
origData := []byte(orig)
k := []byte(key)

block, _ := aes.NewCipher(k)
blockSize := block.BlockSize()
origData = PKCS7Padding(origData, blockSize)
blockMode := cipher.NewCBCEncrypter(block, k[:blockSize])
cryted := make([]byte, len(origData))
blockMode.CryptBlocks(cryted, origData)

return base64.StdEncoding.EncodeToString(cryted)
Enter fullscreen mode Exit fullscreen mode

}

func AesDecrypt(cryted string, key string) string {
crytedByte, _ := base64.StdEncoding.DecodeString(cryted)
k := []byte(key)

block, _ := aes.NewCipher(k)
blockSize := block.BlockSize()
blockMode := cipher.NewCBCDecrypter(block, k[:blockSize])
orig := make([]byte, len(crytedByte))
blockMode.CryptBlocks(orig, crytedByte)
orig = PKCS7UnPadding(orig)

return string(orig)
Enter fullscreen mode Exit fullscreen mode

}

func PKCS7Padding(ciphertext []byte, blocksize int) []byte {
padding := blocksize - len(ciphertext)%blocksize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}

func PKCS7UnPadding(origData []byte) []byte {
length := len(origData)
unpadding := int(origData[length-1])
return origData[:(length - unpadding)]
}

func use_md5() {
h := md5.New()
io.WriteString(h, "md5 encrypt test!")
fmt.Printf("%x\n", h.Sum(nil))
fmt.Printf("%X\n", h.Sum(nil))
}

func use_sha() {
h := sha256.New()
h.Write([]byte("sha256 encrypt test!"))
fmt.Printf("%x\n", h.Sum(nil))
fmt.Printf("%X\n", h.Sum(nil))
}

func main() {
orig := "hello world"
key := "123456781234567812345678"
fmt.Println("encrypt begin:", orig)
encryptCode := AesEncrypt(orig, key)
fmt.Println("encrypt end:", encryptCode)
decryptCode := AesDecrypt(encryptCode, key)
fmt.Println("decode:", decryptCode)
use_md5()
use_sha()
}

Top comments (0)