使用golang中的crypto/des包来进行DES加密,代码如下:

package main

import (
    "crypto/cipher"
    "crypto/des"
    "encoding/base64"
    "fmt"
)

func main() {
    // key必须是长度为8的byte数组
    key := []byte("12345678")
    plaintext := "hello world"
    block, err := des.NewCipher(key)
    if err != nil {
        panic(err)
    }

    // 加密字符串
    ciphertext := make([]byte, len(plaintext))
    block.Encrypt(ciphertext, []byte(plaintext))

    // 将加密结果转为base64字符串
    encoded := base64.StdEncoding.EncodeToString(ciphertext)
    fmt.Println(encoded)

    // 解密字符串
    decoded, err := base64.StdEncoding.DecodeString(encoded)
    if err != nil {
        panic(err)
    }
    decrypted := make([]byte, len(decoded))
    block.Decrypt(decrypted, decoded)
    fmt.Println(string(decrypted))
}

注意,加密的字符串中不能包含斜杠,否则会导致解密失败。如果确实需要加密包含斜杠的字符串,可以使用其他编码方式,如base64编码。

golang 使用des加密方式 加密字符串 不包含斜杠

原文地址: https://www.cveoy.top/t/topic/tFC 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录