简体   繁体   中英

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.

Please change

byte[] privateKeyBytes = publicKey.getEncoded();

with

byte[] privateKeyBytes = privateKey.getEncoded();

the rest of the code seems correct

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM