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

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

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()中可以看到一个示例:

  1. func (p *PemKey) savePrivateKey(privateKey *rsa.PrivateKey, filename string) error {
  2. raw := x509.MarshalPKCS1PrivateKey(privateKey)
  3. block := &pem.Block{
  4. Type: "RSA PRIVATE KEY",
  5. Bytes: raw,
  6. }
  7. file, err := os.Create(filename)
  8. if err != nil {
  9. return err
  10. }
  11. err = pem.Encode(file, block)
  12. if err != nil {
  13. return err
  14. }
  15. return nil
  16. }

公钥的处理方式相同:

  1. func (p *PemKey) savePublicKey(publicKey *rsa.PublicKey, filename string) error {
  2. raw, err := x509.MarshalPKIXPublicKey(publicKey)
  3. if err != nil {
  4. return err
  5. }
  6. block := &pem.Block{
  7. Type: "PUBLIC KEY",
  8. Bytes: raw,
  9. }
  10. file, err := os.Create(filename)
  11. if err != nil {
  12. return err
  13. }
  14. err = pem.Encode(file, block)
  15. if err != nil {
  16. return err
  17. }
  18. return nil
  19. }
英文:

You would need pem.Encode. An example can be seen in maplepie/rsa#savePrivateKey():

  1. func (p *PemKey) savePrivateKey(privateKey *rsa.PrivateKey, filename string) error {
  2. raw := x509.MarshalPKCS1PrivateKey(privateKey)
  3. block := &pem.Block{
  4. Type: "RSA PRIVATE KEY",
  5. Bytes: raw,
  6. }
  7. file, err := os.Create(filename)
  8. if err != nil {
  9. return err
  10. }
  11. err = pem.Encode(file, block)
  12. if err != nil {
  13. return err
  14. }
  15. return nil
  16. }

Same idea for public key:

  1. func (p *PemKey) savePublicKey(publicKey *rsa.PublicKey, filename string) error {
  2. raw, err := x509.MarshalPKIXPublicKey(publicKey)
  3. if err != nil {
  4. return err
  5. }
  6. block := &pem.Block{
  7. Type: "PUBLIC KEY",
  8. Bytes: raw,
  9. }
  10. file, err := os.Create(filename)
  11. if err != nil {
  12. return err
  13. }
  14. err = pem.Encode(file, block)
  15. if err != nil {
  16. return err
  17. }
  18. return nil
  19. }

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:

确定