Add Password to Private Key using OpenSSL

Add Password to Private Key using OpenSSL

Private keys may be protected with a password, which is used in the encryption process. This tutorial demonstrates how to add password to private key using OpenSSL.

Let's say we have the following private key:

-----BEGIN PRIVATE KEY-----
MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEA3+i8CaGg06cTZWgl
5S6ekQH4LBPI9sojxWdD6strvmuIG2Z9isZ1QPwK/+n6KgvzrHBK9f4dheeQ998R
dzsiVQIDAQABAkA3eyS0wj7mkvykYPUa371csv86dMCUHixU6qySjkspSGcvdqNQ
UuAfRJ97n8m8wkNSHhF2HIWH2lPdC/MsZX/VAiEA8QLAZXzsUiEIQ04enLZRq0cv
YkD8mLyXVpT56ZrdEDsCIQDt1bMedIH1kCcAvg4PHAugXw1NeJSvpOpUqOyPwmB+
rwIhAJDhq5EW4OWaT+JOAt8IRt4k49o34OFcdcmpsvZ4jy3jAiA7n+2N3wuNspv0
lbEUnKVViT7egzJTbnbIzqivyb1DRQIhAKbr3cYY4mk0HKFQg3oEhWi2stSPulYz
KNkxLcXmqXjr
-----END PRIVATE KEY-----

The openssl pkcs8 command can be used to process private keys in PKCS#8 format. Run the following command to encrypt private key using password:

openssl pkcs8 -topk8 -in test.key -out test.enc.key

A part of the output:

-----BEGIN ENCRYPTED PRIVATE KEY-----
MIIBvTBXBgkqhkiG9w0BBQ0wSjApBgkqhkiG9w0BBQwwHAQIAUPKeFunkIwCAggA
...
L+FyOXpxqwSFNxjp7M0TxjQ=
-----END ENCRYPTED PRIVATE KEY-----

Command prompts a user to enter a password. It also can be provided directly in command line using -passout option:

openssl pkcs8 -topk8 -passout "pass:testing123" -in test.key -out test.enc.key

The meaning of options:

  • -topk8 - reads a private key and writes a private key in PKCS#8 format.
  • -passout "pass:testing123" - allows to provide a password to encrypt private key.
  • -in test.key - specifies the filename to read a private key.
  • -out test.enc.key - specifies the filename to write a private key.

Leave a Comment

Cancel reply

Your email address will not be published.