Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $YECBGYFECGEAFWHA as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2

Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $BBWFDDBHHYHDXXAB as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2
Node.js废弃加密方法如何用Golang安全地重构?_创想鸟

Node.js废弃加密方法如何用Golang安全地重构?

Golang安全重构Node.js废弃加密方法

本文介绍如何使用golang安全地重构一个使用了node.js废弃加密方法crypto.createcipher('aes256', key)的项目。该node.js代码存在安全漏洞,因为它缺少盐值和明确的加密模式。我们将分析原代码并提供安全的golang实现。

Node.js废弃加密方法如何用Golang安全地重构?

原Node.js代码:

加密函数:

createtoken(src, timestamp, key) {    const msg = src + '|' + timestamp;    const cipher = crypto.createCipher('aes256', key);    let enc = cipher.update(msg, 'utf8', 'hex');    enc += cipher.final('hex');    return enc;}

解密函数:

立即学习“go语言免费学习笔记(深入)”;

parsetoken(token, key) {    const decipher = crypto.createDecipher('aes256', key);    let dec;    try {        dec = decipher.update(token, 'hex', 'utf8');        dec += decipher.final('utf8');    } catch (err) {        return null;    }    const ts = dec.split('|');    if (ts.length !== 2) {        return null;    }    return {src: ts[0], timestamp: Number(ts[1])};}

这段代码使用crypto.createCipher('aes256', key)进行AES-256加密,但未指定加密模式和填充方式,存在安全风险。

安全的Golang重构:

由于原代码未指定加密模式,我们假设其使用了CBC模式(一种常见的块密码模式)。 为了提高安全性,我们将添加随机生成的初始化向量(IV)和PKCS7填充。

package mainimport (    "crypto/aes"    "crypto/cipher"    "crypto/rand"    "encoding/hex"    "fmt"    "io")// PKCS7Padding adds PKCS7 padding to a byte array.func PKCS7Padding(ciphertext []byte, blockSize int) []byte {    padding := blockSize - len(ciphertext)%blockSize    padtext := bytes.Repeat([]byte{byte(padding)}, padding)    return append(ciphertext, padtext...)}// PKCS7UnPadding removes PKCS7 padding from a byte array.func PKCS7UnPadding(origData []byte) []byte {    length := len(origData)    unpadding := int(origData[length-1])    return origData[:(length - unpadding)]}func encrypt(src, timestamp string, key []byte) (string, error) {    msg := []byte(src + "|" + timestamp)    block, err := aes.NewCipher(key)    if err != nil {        return "", err    }    blockSize := block.BlockSize()    // Generate a random IV    iv := make([]byte, blockSize)    if _, err := io.ReadFull(rand.Reader, iv); err != nil {        return "", err    }    paddedMsg := PKCS7Padding(msg, blockSize)    blockMode := cipher.NewCBCEncrypter(block, iv)    crypted := make([]byte, len(paddedMsg))    blockMode.CryptBlocks(crypted, paddedMsg)    return hex.EncodeToString(append(iv, crypted...)), nil}func decrypt(token string, key []byte) (string, error) {    tokenBytes, err := hex.DecodeString(token)    if err != nil {        return "", err    }    iv := tokenBytes[:aes.BlockSize]    crypted := tokenBytes[aes.BlockSize:]    block, err := aes.NewCipher(key)    if err != nil {        return "", err    }    blockMode := cipher.NewCBCDecrypter(block, iv)    origData := make([]byte, len(crypted))    blockMode.CryptBlocks(origData, crypted)    unpaddedData := PKCS7UnPadding(origData)    return string(unpaddedData), nil}func main() {    key := []byte("your_32_byte_secret_key") // Replace with a 32-byte key    src := "your_source_data"    timestamp := "1678886400" // Example timestamp    encrypted, err := encrypt(src, timestamp, key)    if err != nil {        fmt.Println("Encryption error:", err)        return    }    fmt.Println("Encrypted:", encrypted)    decrypted, err := decrypt(encrypted, key)    if err != nil {        fmt.Println("Decryption error:", err)        return    }    fmt.Println("Decrypted:", decrypted)}

关键改进:

密钥长度: 使用32字节的密钥 (AES-256)。加密模式: 明确使用CBC模式。初始化向量 (IV): 随机生成IV,并将其与密文一起存储和传输,确保每次加密的结果不同,增强安全性。填充: 使用PKCS7填充,避免填充攻击。错误处理: 添加了更完善的错误处理。

重要提示:

替换 "your_32_byte_secret_key" 为实际的32字节密钥。 密钥管理至关重要,请妥善保管密钥。这个代码示例假设使用了CBC模式。如果原Node.js代码使用了其他模式,需要相应调整Golang代码。在生产环境中,建议使用更高级的加密库和更安全的密钥管理机制。 避免直接将密钥硬编码在代码中。

此Golang版本提供了更安全可靠的加密和解密功能,解决了原Node.js代码中的安全漏洞。 记住,安全编码需要谨慎,并根据实际情况选择合适的加密算法和策略。

以上就是Node.js废弃加密方法如何用Golang安全地重构?的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1385517.html

赞 (0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
EMQX、Go-Gin设备通信:认证、指令发送及业务处理如何实现?
上一篇 2025年12月15日 05:13:50
Go语言中顶格书写的Label是什么以及如何使用?
下一篇 2025年12月15日 05:13:59

相关推荐

发表回复

登录后才能评论
关注微信