英文:
How to write *PrivateKey type variable to a file in golang?
问题
我已经使用go语言的crypto/rsa库生成了一个RSA私钥和相应的公钥。现在我想将它们分别写入两个文件中,但是WriteString和Write函数只适用于字符串和字节切片变量。而且像String(privateKey)这样的指令会生成错误。我该如何将这些密钥写入文件中呢?
英文:
I have generated a RSA private key (using crypto/rsa) and corresponding public key in go. Now I want to write them to two files (each one to a file), but WriteString and Write functions are specific to string and []byte variable. Also instructions like String(privateKey) generate error. How I can write these keys to the files?
答案1
得分: 1
你需要使用pem.Encode
函数进行编码。在maplepie/rsa#savePrivateKey()
中可以看到一个示例:
func (p *PemKey) savePrivateKey(privateKey *rsa.PrivateKey, filename string) error {
raw := x509.MarshalPKCS1PrivateKey(privateKey)
block := &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: raw,
}
file, err := os.Create(filename)
if err != nil {
return err
}
err = pem.Encode(file, block)
if err != nil {
return err
}
return nil
}
公钥的处理方式相同:
func (p *PemKey) savePublicKey(publicKey *rsa.PublicKey, filename string) error {
raw, err := x509.MarshalPKIXPublicKey(publicKey)
if err != nil {
return err
}
block := &pem.Block{
Type: "PUBLIC KEY",
Bytes: raw,
}
file, err := os.Create(filename)
if err != nil {
return err
}
err = pem.Encode(file, block)
if err != nil {
return err
}
return nil
}
英文:
You would need pem.Encode
. An example can be seen in maplepie/rsa#savePrivateKey()
:
func (p *PemKey) savePrivateKey(privateKey *rsa.PrivateKey, filename string) error {
raw := x509.MarshalPKCS1PrivateKey(privateKey)
block := &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: raw,
}
file, err := os.Create(filename)
if err != nil {
return err
}
err = pem.Encode(file, block)
if err != nil {
return err
}
return nil
}
Same idea for public key:
func (p *PemKey) savePublicKey(publicKey *rsa.PublicKey, filename string) error {
raw, err := x509.MarshalPKIXPublicKey(publicKey)
if err != nil {
return err
}
block := &pem.Block{
Type: "PUBLIC KEY",
Bytes: raw,
}
file, err := os.Create(filename)
if err != nil {
return err
}
err = pem.Encode(file, block)
if err != nil {
return err
}
return nil
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论