3

What is the equivalent of the following command in Go?

openssl genrsa -des3 -passout pass:mypassword -out myfile.key 2048

What I have so far...

package main

import (
    "crypto/des"
    "crypto/rand"
    "crypto/rsa"
    "encoding/pem"
)

func main() {
  key, _ := rsa.GenerateKey(rand.Reader, 2048)

  // Do something with des.NewTripleDESCipher(...)?

  keyPem := pem.EncodeToMemory(&pem.Block{
    Type:  "RSA PRIVATE KEY",
    Bytes: ?,
  })

  // ...
}
Sam Herrmann
  • 6,293
  • 4
  • 31
  • 50

1 Answers1

4

The main thing you're missing is the x509.EncryptPEMBlock function which can be used to encrypt with one of multiple ciphers, including 3DES.

Here is sample code to generate a key, encrypt it with 3DES, and write it to a file:

package main

import (
  "crypto/rand"
  "crypto/rsa"
  "crypto/x509"
  "encoding/pem"
  "io/ioutil"
)

func main() {
  // Generate a 2048 bit RSA key.
  key, err := rsa.GenerateKey(rand.Reader, 2048)
  if err != nil {
    panic(err)
  }

  // Marshal it into DER-encoded ASN.1 format.
  raw := x509.MarshalPKCS1PrivateKey(key)

  // Encrypt using 3DES and password "mypassword".
  block, err := x509.EncryptPEMBlock(rand.Reader, "RSA PRIVATE KEY", raw, []byte("mypassword"), x509.PEMCipher3DES)
  if err != nil {
    panic(err)
  }

  // Encode the block into PEM.
  encoded := pem.EncodeToMemory(block)

  // Write it out.
  err = ioutil.WriteFile("myfile.key", encoded, 0400)
  if err != nil {
    panic(err)
  }
}

The generated file is:

-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,627721fef197aa1f

Y5BPGXBnrTXgSPfWGl04f9FNJAB8tlzOF3MBUJaZBBb+3sOWWfz43RikFuXowl3s
DWOjNv9TnHO1M5Tlxye84iywo8CqINCZzMfan3J8ZxKWHpXbs5DVXQ9INTPfLueq
...
QuUylrQNEWt0T1BlKRltAkoRawiBj7Ys/WMnto9dfEbJPeoHfGCp0xTSYSvIwE01
rYrebCfNdrb8gW4KlQnOCj0bHU6xDtLzMtt6i9JD4CtXGKBo8mYwng==
-----END RSA PRIVATE KEY-----

Word of advice: 3DES is considered a weak cipher. You should use AES instead (available in multiple key sizes).

Marc
  • 19,394
  • 6
  • 47
  • 51
  • As if the API was made for it :P – Maarten Bodewes Sep 13 '20 at 10:36
  • Excellent, works like a charm! Thanks for the advise! I am a novice when it comes to cryptography. My main source of info so far has been this post (https://stackoverflow.com/a/60516812/3634032). I am surprised that given how many views that post has gotten over the years, that no one commented on the cipher (unless I overlooked it). – Sam Herrmann Sep 13 '20 at 18:27