Last active
August 15, 2019 12:48
-
-
Save gsandaru/8eb47cb390dec18ab1bc640f54f642fe to your computer and use it in GitHub Desktop.
Java,Android - Get RSAPrivateKey and RSAPublicKey from String
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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