10

I'm trying to encrypt some content with an RSA private key.

I'm following this example: http://www.junkheap.net/content/public_key_encryption_java

but converting it to use private keys rather than public. Following that example, I think what I need to do is:

  • Read in a DER-format private key
  • Generate a PCKS8EncodedKeySpec
  • call generatePrivate() from KeyFactory to get a private key object
  • Use that private key object with the Cipher object to do the encryption

So, the steps:

The key was generated from openssl with:

openssl genrsa -aes256 -out private.pem 2048

and then was converted to DER format with:

openssl rsa -in private.pem -outform DER -out private.der

I generate the PKCS8EncodedKeySpec with:

byte[] encodedKey = new byte[(int)inputKeyFile.length()];

try {
    new FileInputStream(inputKeyFile).read(encodedKey);
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedKey);
return privateKeySpec;

And then generate the private key object with:

PrivateKey pk = null;

try {
    KeyFactory kf = KeyFactory.getInstance(RSA_METHOD);
    pk = kf.generatePrivate(privateKeySpec);
} catch (NoSuchAlgorithmException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (InvalidKeySpecException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
return pk;

However, on the call to:

pk = kf.generatePrivate(privateKeySpec);

I get:

java.security.spec.InvalidKeySpecException: Unknown key spec.
at com.sun.net.ssl.internal.ssl.JS_KeyFactory.engineGeneratePrivate(DashoA12275)
at com.sun.net.ssl.internal.ssl.JSA_RSAKeyFactory.engineGeneratePrivate(DashoA12275)
at java.security.KeyFactory.generatePrivate(KeyFactory.java:237)

Questions:

  • Is the general approach right?
  • Is the PCKS8EncodedKeySpec the right keyspec to use?
  • Any thoughts on the invalid key spec error?
1

5 Answers 5

11

You can't encrypt with private key. If JCE allows you to do that, it's just by accident.

You need to use signature. Here are the code snippet to do that,

signer = Signature.getInstance("SHA1withRSA");
signer.initSign(privateKey); // PKCS#8 is preferred
signer.update(dataToSign);
byte[] signature = signer.sign();
1
  • 1
    s/public/private/ in your first line.
    – caf
    Sep 8, 2009 at 13:43
8

First of all, I'm confused why you are planning to use a Cipher to encrypt with a private key, rather than signing with a Signature. I'm not sure that all RSA Cipher providers will use the correct block type for setup, but it's worth a try.

Setting that aside, though, I think that you are trying to load a non-standard OpenSSL-format key. Converting it to DER with rsa is essentially just a base-64 decode; the structure of the key is not PKCS #8.

Instead, after genrsa, use the openssl pkcs8 command to convert the generated key to unencrypted PKCS #8, DER format:

openssl pkcs8 -topk8 -nocrypt -in private.pem -outform der -out private.der

This will produce an unencrypted private key that can be loaded with a PKCS8EncodedKeySpec.

8
  • Honestly, I was unaware of Signature. To make sure I understand its usage, I would initialize the signature object, call update with the bytes I want to sign, and then call sign? And then I can store the bytes returned from sign as my digital signature?
    – wadesworld
    Sep 8, 2009 at 5:32
  • Hello. Anyone finally resolved the problem? I have a privateKey That I cannot load into java to continue wiht signing phase. My privateKey is RSA, PKCS#8 DER and it has a password. How can I load that into java? The exception in my case is java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException : DER input, Integer tag error
    – BRabbit27
    Dec 9, 2011 at 23:30
  • @BRabbit27 To load a private key directly, it must be unencrypted. Use the openssl pkcs8 command I show above, adding the option -inform der; it will prompt you for the password. If you want to keep your private key encrypted (which I highly recommend), you'll need to add it to a key store (like a PKCS #12 file), and access it through the KeyStore API in Java.
    – erickson
    Dec 10, 2011 at 0:30
  • @erickson I tried the command but it shows an error (I'm using WinOpenSSL) error decrypting key. The command I used was openssl pkcs8 -topk8 -nocrypt -in myKey.key -inform der -outform der -out myNoCryptKey.key
    – BRabbit27
    Dec 12, 2011 at 15:15
  • UPDATE What's supposed to do the -nocrypt option? I think I made a workaround like this openssl pkcs8 -inform DER -in myKey.key -outform PEM -out myKeyInPEM.key it asked me for my password and then openssl pkcs8 -topk8 -nocrypt -in myKeyInPEM -outform DER -out myKeyInDERNoCrypted.key it didn't ask my password but the result file seems equal to myKey.key
    – BRabbit27
    Dec 12, 2011 at 15:26
4

Its not an accident that encryption with private key is allowed. If you want to break a signature into individual hashing and encryption, then encrypting with private key is essential. Lets say I have a document which i need to sign and my key resides on a network HSM. Now either I stream the entire document to the HSM to sign or I can create a local hash and stream it to the HSM for encryption alone. My choice will depend on whether the local hash computation gives me better performance viz a viz delegated hash computation with network latency.

0
3

This question is pretty old, but I recently stumbled upon the problem (I'm implementing requirements of some protocol which requires encryption with private key). I will just quote the post from forum:

I recently stumbled upon the same issue, submitted PMR 22265,49R, and IBM Support after consultation with "development" (whoever those are) ruled that private keys cannot be used for encryption. No matter how much I tried to argue with them that private keys should not be used for data protection, which is only one purpose behind encryption, and that it is perfectly fine to use private keys for encryption to achieve non-repudiation, they were unshakable in their belief. You have got to love people, who insist that 2x2=5.

Here is how I worked around this problem: Essentially, I created a public key object with private key's crypto material. You will need to do the reverse, create a private key object with public key's crypto material, to decrypt with public key if you want to avoid the "Public key cannot be used to decrypt" exception.

RSAPrivateCrtKey privateKey = (RSAPrivateCrtKey) ks.getKey(keyAlias, ksPassword.trim().toCharArray());
RSAPublicKeySpec spec = new RSAPublicKeySpec(
   privateKey.getModulus(),
   privateKey.getPrivateExponent()
);
Key fakePublicKey = KeyFactory.getInstance("RSA").generatePublic(spec);
encryptCipher.init(Cipher.ENCRYPT_MODE, fakePublicKey);
3
  • 1
    That is very risky if you treat the private key exponent as the public exponent and distribute it, because given the private key (which you are calling the "public key") it is easy to derive the actual public key (which you are now calling the "private key"). Don't accidently let that "public key" out in public, or your system will be compromised. It may be as simple as guessing that the exponent of the "private key" is 65537.
    – Jim Flood
    May 23, 2014 at 22:06
  • I was searching for this so long. I'm so thankful for this answer. The name "private and public key" is totally wrong in this use case but there are situations where this is relevant.
    – Ramon
    Jun 30, 2015 at 17:09
  • 1
    @JimFlood If I understand correctly, and my situation is similar, dmitry created an RSAPublicKeySpec to hold the private key data. Obviously he's not going to distribute the private key, just the original public key that can now be used to prove (decrypt) that the private key was for encryption - i.e. non-repudiation.
    – Guss
    Jul 24, 2017 at 15:27
0

try this:

java.security.Security.addProvider(
                     new org.bouncycastle.jce.provider.BouncyCastleProvider()
            );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.