Skip to content

Instantly share code, notes, and snippets.

@gsandaru
Last active August 15, 2019 12:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gsandaru/8eb47cb390dec18ab1bc640f54f642fe to your computer and use it in GitHub Desktop.
Save gsandaru/8eb47cb390dec18ab1bc640f54f642fe to your computer and use it in GitHub Desktop.
Java,Android - Get RSAPrivateKey and RSAPublicKey from String
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
try {
String privateKeyContent = sharedPreferences.getString("SAMPLE_KEY_PRI",null); // load private key here
String publicKeyContent = sharedPreferences.getString("SAMPLE_KEY_PUB",null); //load public key here
privateKeyContent = privateKeyContent.replaceAll("\\n", "")
.replace("-----BEGIN PRIVATE KEY-----", "")
.replace("-----END PRIVATE KEY-----", "")
.replaceAll("\\s+","");
publicKeyContent = publicKeyContent.replaceAll("\\n", "")
.replace("-----BEGIN PRIVATE KEY-----", "")
.replace("-----END PRIVATE KEY-----", "")
.replaceAll("\\s+","");
KeyFactory kf = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec keySpecPKCS8 = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKeyContent));
RSAPrivateKey privKey = (RSAPrivateKey) kf.generatePrivate(keySpecPKCS8);
X509EncodedKeySpec keySpecX509 = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKeyContent));
RSAPublicKey pubKey = (RSAPublicKey) kf.generatePublic(keySpecX509);
}catch (Exception e){
e.printStackTrace();
}
// Used with lib ==> implementation 'com.blakequ.rsa:rsa:1.1'
//
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment