登录
首页 >  Golang >  Go问答

对消息进行加密以保护安全

来源:stackoverflow

时间:2024-02-22 09:36:18 304浏览 收藏

学习Golang要努力,但是不要急!今天的这篇文章《对消息进行加密以保护安全》将会介绍到等等知识点,如果你想深入学习Golang,可以关注我!我会持续更新相关文章的,希望对大家都能有所帮助!

问题内容

我需要使用公钥来加密消息“message”,并通过将预先接收到的数据转换为十六进制编码,将其保存为文件ciphertext.txt。我不需要生成公钥,我已经有一个现成的公钥。使用此公钥,您需要加密消息。 这是我能做的:

package main

import (
"crypto/rand" 
"crypto/rsa"
"crypto/sha256" 
"crypto/x509" 
"encoding/pem" 
"errors"
"log"
"os"
)

func main() {
publicKeyBytes, err := os.ReadFile("publicik.key")
if err!= nil {
    return
} 
publicKey, err := decodepublicKey(publicKeyBytes)
if  err != nil {
    return
}
plaintext := []byte("Message")
ciphertext, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, publicKey, plaintext, nil)
if err != nil {
    return
}
log.Printf( "%x", ciphertext)

privateKeyBytes, err := os.ReadFile("private.key")
if err != nil {
    return
}
privateKey, err := decodePrivateKey(privateKeyBytes)
if err != nil {
    return  
}
decryptedtext, err := rsa.DecryptOAEP(sha256.New(), rand.Reader, privateKey,ciphertext, nil)
if  err != nil {
    return
}
log.Printf("%s", decryptedtext)
}

func decodepublicKey(key []byte) (*rsa.PublicKey, error) {
    block, _:= pem.Decode(key) 
    if block == nil {
    return nil, errors.New("can't decode pem block")
    }
    publicKey, err := x509.ParsePKCS1PublicKey(block.Bytes) 
    if err != nil {
    return nil, err
    }
    return publicKey, nil
    }

func decodePrivateKey(key []byte) (*rsa.PrivateKey,error) { block, _ := pem.Decode(key)
    if block ==  nil {
    return nil, errors.New("can't decode pem block")
    }
    privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes) 
    if err != nil {
    return nil, err
    }
    return privateKey, nil
}

那我不知道如何解决这个问题? 请帮忙解决这个问题


正确答案


我调试了您的代码并发现了 2 个潜在问题:

  1. 仔细检查是否需要使用 x509.ParsePKCS1PublicKey()x509.ParsePKIXPublicKey()。这取决于您的公钥的格式。更多信息请点击:https://stackoverflow.com/a/54775627/9698467
  2. 您可能需要在 decodepublicKey 函数中输入断言公钥:return publicKey.(*rsa.PublicKey), nil

今天关于《对消息进行加密以保护安全》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>