Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert String to Private key?

I am trying to convert a string that I stored in the SharedPreferences to PrivateKey but I am unable to do so.

This is how I am converting the PrivateKey to String,

kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024);
kp = kpg.genKeyPair();
publicKey = kp.getPublic();
privateKey = kp.getPrivate();

byte[] privateKeyBytes = publicKey.getEncoded();
String privKeyStr = new String(Base64.encode(privateKeyBytes));

SharedPreferences.Editor editor = getPrefs(context).edit();
editor.putString(user + "_private_key", privKeyStr + "");
editor.commit();

And this is how I am trying to retrieve the key from the SharedPreference and converting it back to PrivateKey

String privKeyStr = getPrefs(context).getString(user + "_private_key", "no private key");
Log.d("key", privKeyStr);
byte[] sigBytes = new byte[0];
try {
    sigBytes = Base64.decode(privKeyStr.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
}
PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(sigBytes);
KeyFactory keyFact = KeyFactory.getInstance("RSA");
PrivateKey privateKey = null;

try {
    privateKey = keyFact.generatePrivate(privateKeySpec);  //throws exception
} catch (InvalidKeySpecException e) {
    e.printStackTrace();
}

and this is the error that I keep receiving,

java.security.spec.InvalidKeySpecException: java.lang.RuntimeException: error:0c0000b9:ASN.1 encoding routines:OPENSSL_internal:WRONG_TAG

I know that questions similar to this have already been asked before, but none of them seemed to solve my problem.

Please, help me know where I am going wrong.

like image 783
Vishist Varugeese Avatar asked Nov 02 '25 02:11

Vishist Varugeese


1 Answers

Please change

byte[] privateKeyBytes = publicKey.getEncoded();

with

byte[] privateKeyBytes = privateKey.getEncoded();

the rest of the code seems correct

like image 102
pedrofb Avatar answered Nov 03 '25 17:11

pedrofb