RSA 加密解密
    package main

    import (
    “crypto/rand”
    “crypto/rsa”
    “crypto/x509”
    “encoding/hex”
    “encoding/pem”
    “fmt”
    “os”
    )

    //生成RSA私钥和公钥,保存到文件中
    func GenerateRSAKey(bits int) {
    //GenerateKey函数使用随机数据生成器random生成一对具有指定字位数的RSA密钥
    //Reader是一个全局、共享的密码用强随机数生成器
    privateKey, err := rsa.GenerateKey(rand.Reader, bits)
    if err != nil {
    panic(err)
    }
    //保存私钥
    //通过x509标准将得到的ras私钥序列化为ASN.1 的 DER编码字符串
    X509PrivateKey := x509.MarshalPKCS1PrivateKey(privateKey)
    //使用pem格式对x509输出的内容进行编码
    //创建文件保存私钥
    privateFile, err := os.Create(“private.pem”)
    if err != nil {
    panic(err)
    }
    defer privateFile.Close()
    //构建一个pem.Block结构体对象
    privateBlock := pem.Block{Type: “RSA Private Key”, Bytes: X509PrivateKey}
    //将数据保存到文件
    pem.Encode(privateFile, &privateBlock)

    //保存公钥
    //获取公钥的数据
    publicKey := privateKey.PublicKey
    //X509对公钥编码
    X509PublicKey, err := x509.MarshalPKIXPublicKey(&publicKey)
    if err != nil {
    panic(err)
    }
    //pem格式编码
    //创建用于保存公钥的文件
    publicFile, err := os.Create(“public.pem”)
    if err != nil {
    panic(err)
    }
    defer publicFile.Close()
    //创建一个pem.Block结构体对象
    publicBlock := pem.Block{Type: “RSA Public Key”, Bytes: X509PublicKey}
    //保存到文件
    pem.Encode(publicFile, &publicBlock)
    }

    //RSA加密
    func RSAEncrypt(plainText []byte, path string) []byte {
    //打开文件
    file, err := os.Open(path)
    if err != nil {
    panic(err)
    }
    defer file.Close()
    //读取文件的内容
    info,
    := file.Stat()
    buf := make([]byte, info.Size())
    file.Read(buf)
    //pem解码
    block, _ := pem.Decode(buf)
    //x509解码

    publicKeyInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
    if err != nil {
    panic(err)
    }
    //类型断言
    publicKey := publicKeyInterface.(*rsa.PublicKey)
    //对明文进行加密
    cipherText, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey, plainText)
    if err != nil {
    panic(err)
    }
    //返回密文
    return cipherText
    }

    //RSA解密
    func RSADecrypt(cipherText []byte, path string) []byte {
    //打开文件
    file, err := os.Open(path)
    if err != nil {
    panic(err)
    }
    defer file.Close()
    //获取文件内容
    info,
    := file.Stat()
    buf := make([]byte, info.Size())
    file.Read(buf)
    //pem解码
    block, := pem.Decode(buf)
    //X509解码
    privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
    if err != nil {
    panic(err)
    }
    //对密文进行解密
    plainText,
    := rsa.DecryptPKCS1v15(rand.Reader, privateKey, cipherText)
    //返回明文
    return plainText
    }
    func main() {
    //生成密钥对,保存到文件
    GenerateRSAKey(2048)
    message := []byte(“hello world”)
    //加密
    cipherText := RSA_Encrypt(message, “public.pem”)
    fmt.Println(“加密后为:”, hex.EncodeToString(cipherText))
    //解密
    plainText := RSA_Decrypt(cipherText, “private.pem”)
    fmt.Println(“解密后为:”, string(plainText))
    }

    Crypto AES加密 (ECB,CBC,CFB)
    package main

    import (
    “bytes”
    “crypto/aes”
    “crypto/cipher”
    “crypto/rand”
    “encoding/base64”
    “encoding/hex”
    “io”
    “log”
    )

    func main() {
    origData := []byte(“Hello World”) // 待加密的数据
    key := []byte(“ABCDEFGHIJKLMNOP”) // 加密的密钥
    log.Println(“原文:”, string(origData))

    log.Println(“————————— CBC模式 ——————————“)
    encrypted := AesEncryptCBC(origData, key)
    log.Println(“密文(hex):”, hex.EncodeToString(encrypted))
    log.Println(“密文(base64):”, base64.StdEncoding.EncodeToString(encrypted))
    decrypted := AesDecryptCBC(encrypted, key)
    log.Println(“解密结果:”, string(decrypted))

    log.Println(“————————— ECB模式 ——————————“)
    encrypted = AesEncryptECB(origData, key)
    log.Println(“密文(hex):”, hex.EncodeToString(encrypted))
    log.Println(“密文(base64):”, base64.StdEncoding.EncodeToString(encrypted))
    decrypted = AesDecryptECB(encrypted, key)
    log.Println(“解密结果:”, string(decrypted))

    log.Println(“————————— CFB模式 ——————————“)
    encrypted = AesEncryptCFB(origData, key)
    log.Println(“密文(hex):”, hex.EncodeToString(encrypted))
    log.Println(“密文(base64):”, base64.StdEncoding.EncodeToString(encrypted))
    decrypted = AesDecryptCFB(encrypted, key)
    log.Println(“解密结果:”, string(decrypted))
    }

    // =================== CBC ======================
    func AesEncryptCBC(origData []byte, key []byte) (encrypted []byte) {
    // 分组秘钥
    // NewCipher该函数限制了输入k的长度必须为16, 24或者32
    block, := aes.NewCipher(key)
    blockSize := block.BlockSize() // 获取秘钥块的长度
    origData = pkcs5Padding(origData, blockSize) // 补全码
    blockMode := cipher.NewCBCEncrypter(block, key[:blockSize]) // 加密模式
    encrypted = make([]byte, len(origData)) // 创建数组
    blockMode.CryptBlocks(encrypted, origData) // 加密
    return encrypted
    }
    func AesDecryptCBC(encrypted []byte, key []byte) (decrypted []byte) {
    block,
    := aes.NewCipher(key) // 分组秘钥
    blockSize := block.BlockSize() // 获取秘钥块的长度
    blockMode := cipher.NewCBCDecrypter(block, key[:blockSize]) // 加密模式
    decrypted = make([]byte, len(encrypted)) // 创建数组
    blockMode.CryptBlocks(decrypted, encrypted) // 解密
    decrypted = pkcs5UnPadding(decrypted) // 去除补全码
    return decrypted
    }
    func pkcs5Padding(ciphertext []byte, blockSize int) []byte {
    padding := blockSize - len(ciphertext)%blockSize
    padtext := bytes.Repeat([]byte{byte(padding)}, padding)
    return append(ciphertext, padtext…)
    }
    func pkcs5UnPadding(origData []byte) []byte {
    length := len(origData)
    unpadding := int(origData[length-1])
    return origData[:(length - unpadding)]
    }

    // =================== ECB ======================
    func AesEncryptECB(origData []byte, key []byte) (encrypted []byte) {
    cipher, _ := aes.NewCipher(generateKey(key))
    length := (len(origData) + aes.BlockSize) / aes.BlockSize
    plain := make([]byte, length*aes.BlockSize)
    copy(plain, origData)
    pad := byte(len(plain) - len(origData))
    for i := len(origData); i < len(plain); i++ {
    plain[i] = pad
    }
    encrypted = make([]byte, len(plain))
    // 分组分块加密
    for bs, be := 0, cipher.BlockSize(); bs <= len(origData); bs, be = bs+cipher.BlockSize(), be+cipher.BlockSize() {
    cipher.Encrypt(encrypted[bs:be], plain[bs:be])
    }

    return encrypted
    }
    func AesDecryptECB(encrypted []byte, key []byte) (decrypted []byte) {
    cipher, _ := aes.NewCipher(generateKey(key))
    decrypted = make([]byte, len(encrypted))
    //
    for bs, be := 0, cipher.BlockSize(); bs < len(encrypted); bs, be = bs+cipher.BlockSize(), be+cipher.BlockSize() {
    cipher.Decrypt(decrypted[bs:be], encrypted[bs:be])
    }

    trim := 0
    if len(decrypted) > 0 {
    trim = len(decrypted) - int(decrypted[len(decrypted)-1])
    }

    return decrypted[:trim]
    }
    func generateKey(key []byte) (genKey []byte) {
    genKey = make([]byte, 16)
    copy(genKey, key)
    for i := 16; i < len(key); {
    for j := 0; j < 16 && i < len(key); j, i = j+1, i+1 {
    genKey[j] ^= key[i]
    }
    }
    return genKey
    }

    // =================== CFB ======================
    func AesEncryptCFB(origData []byte, key []byte) (encrypted []byte) {
    block, err := aes.NewCipher(key)
    if err != nil {
    panic(err)
    }
    encrypted = make([]byte, aes.BlockSize+len(origData))
    iv := encrypted[:aes.BlockSize]
    if , err := io.ReadFull(rand.Reader, iv); err != nil {
    panic(err)
    }
    stream := cipher.NewCFBEncrypter(block, iv)
    stream.XORKeyStream(encrypted[aes.BlockSize:], origData)
    return encrypted
    }
    func AesDecryptCFB(encrypted []byte, key []byte) (decrypted []byte) {
    block,
    := aes.NewCipher(key)
    if len(encrypted) < aes.BlockSize {
    panic(“ciphertext too short”)
    }
    iv := encrypted[:aes.BlockSize]
    encrypted = encrypted[aes.BlockSize:]

    stream := cipher.NewCFBDecrypter(block, iv)
    stream.XORKeyStream(encrypted, encrypted)
    return encrypted
    }