使用go来做加密解密文件或者字符串

你可以使用 Linux 命令行中的 opensslgpg 进行加密,然后在 Go 程序中使用相关的库来解密。

方案 1: 使用 OpenSSL 进行加密,Go 程序解密

1. 命令行加密

使用 openssl 在命令行中对 token 进行加密,并保存加密结果:

echo -n "your_token" | openssl enc -aes-256-cbc -a -salt -pass pass:your_password > encrypted_token.txt
  • your_token: 要加密的 token。
  • aes-256-cbc: 加密算法。
  • your_password: 加密时使用的密码。
  • -a: 使用 base64 编码输出。

这会将加密后的数据保存到 encrypted_token.txt 文件中。

2. Go 程序解密

在 Go 中,可以使用 crypto/aescrypto/cipher 包来解密 openssl 生成的加密数据。

package main

import (
    "crypto/aes"
    "crypto/cipher"
    "crypto/sha256"
    "encoding/base64"
    "fmt"
    "io/ioutil"
    "log"
)

func main() {
    // 从文件中读取加密的 token
    encryptedData, err := ioutil.ReadFile("encrypted_token.txt")
    if err != nil {
        log.Fatalf("Failed to read encrypted file: %v", err)
    }

    // base64 解码
    ciphertext, err := base64.StdEncoding.DecodeString(string(encryptedData))
    if err != nil {
        log.Fatalf("Failed to decode base64: %v", err)
    }

    // 定义密码并生成密钥 (与加密时的密码相同)
    password := "your_password"
    key := sha256.Sum256([]byte(password)) // 256-bit 密钥

    // 初始化解密器
    block, err := aes.NewCipher(key[:])
    if err != nil {
        log.Fatalf("Failed to create cipher: %v", err)
    }

    // 获取 IV (前 16 字节)
    iv := ciphertext[:aes.BlockSize]
    ciphertext = ciphertext[aes.BlockSize:]

    // 使用 CBC 模式进行解密
    mode := cipher.NewCBCDecrypter(block, iv)
    mode.CryptBlocks(ciphertext, ciphertext)

    // 去除填充(PKCS7 Padding)
    plaintext := string(ciphertext)
    fmt.Println("Decrypted Token:", plaintext)
}

总结

  • OpenSSL 方案使用 crypto/aes 相关库在 Go 中解密。
posted @ 2024-09-12 11:14  jasmine456  阅读(6)  评论(0编辑  收藏  举报