How to write *PrivateKey type variable to a file in golang?

huangapple go评论100阅读模式
英文:

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
}

huangapple
  • 本文由 发表于 2022年10月29日 14:37:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/74243311.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定