Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a RSA private key with Triple DES encryption

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: ?,
  })

  // ...
}
like image 450
Sam Herrmann Avatar asked Jan 31 '26 03:01

Sam Herrmann


1 Answers

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).

like image 127
Marc Avatar answered Feb 02 '26 18:02

Marc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!