It makes no sense to encrypt a file with a private key.
Using a private key to attach a tag to a file that guarantees that the file was provided by the holder of the private key is called signing, and the tag is called a signature.
There is one popular cryptosystem (textbook RSA) where a simplified (insecure) algorithm uses has public and private keys of the same type, and decryption is identical to signature and encryption is identical to verification. This is not the case in general: even RSA uses different mechanisms for decryption and signature (resp. encryption and verification) with proper, secure padding modes; and many other algorithms have private and public keys that aren't even the same kind of mathematical objects.
So you want to sign the file. The de facto standard tool for this is GnuPG.
To sign a file with your secret key:
gpg -s /path/to/file
Use the --local-user
option to select a secret key if you have several (e.g. your app key vs your personal key).
Transfer file.gpg
to the place where you want to use the file. Transfer the public key as well (presumably inside the application bundle). To extract the original text and verify the signature, run
gpg file.gpg
If it's more convenient, you can transfer file
itself, and produce a separate signature file which is called a detached signature. To produce the detached signature:
gpg -b /path/to/file
To verify:
gpg file.gpg file
You can additionally encrypt the file with the -e
option. Of course this means that you need a separate key pair, where the recipient (specified with the -r
option) has the private key and the producer has the public key.
The default hash used by openssl enc
for password-based key derivation changed in 1.1.0 to SHA256 versus MD5 in lower versions. This produces a different key from the same password (and salt if used as it usually is), and trying to encrypt and decrypt with different keys produces garbage, an error, or both.
To fix this for existing data specify -md md5
in 1.1.0 to decrypt data from lower versions, and -md sha256
in lower versions to decrypt data from 1.1.0. Going forward, consider specifying -md
explicitly.
For details see https://crypto.stackexchange.com/questions/3298/is-there-a-standard-for-openssl-interoperable-aes-encryption/35614#35614 (disclosure: mine)
Best Answer
Add
-pass file:nameofkeyfile
to the OpenSSL command line. This causes OpenSSL to read the password/passphrase from the named file, but otherwise proceed normally.For more details, see the man page for openssl(1) (
man 1 openssl
) and particularly its section "PASS PHRASE ARGUMENTS", and the man page for enc(1) (man 1 enc
).If the key file actually holds the encryption key (not something from which to derive the encryption key), then you want to use
-K
instead. For that, you need something like:in the OpenSSL command line instead of
-pass
.hexdump
is used to transform the key file to the pure hexadecimal representation that OpenSSL wants.