Key of string in Java RSA
•
Java
I use RSA encryption in my application To store the generated public key, I convert it to a string and save it in the database
Key publicKey=null; Key privateKey=null; KeyPair keyPair=RsaCrypto.getKeyPairRSA(1024); publicKey=keyPair.getPublic(); privateKey=keyPair.getPrivate(); String publicK=Base64.encodeToString(publicKey.getEncoded(),Base64.DEFAULT); String privateK=Base64.encodeToString(privateKey.getEncoded(),Base64.DEFAULT);
I saved strings, publick and privatek My problem is that when I want to encrypt / decrypt text with RSA and use my saved key in string format, I don't know how to convert it to key
public static String encrypt(Key publicKey,String inputText){ byte[]encodedBytes=null; String encryptedText=""; try { Cipher cipher=Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE,publicKey); encodedBytes=cipher.doFinal(inputText.getBytes()); } catch (Exception e) {Log.e("Error","RSA encryption error"); } encryptedText=Base64.encodeToString(encodedBytes,Base64.DEFAULT); return encryptedText; }
Do you have any ideas? Thank you.
Solution
To convert public K (string) to public key:
byte[] keyBytes = Base64.decode(publicK.getBytes("utf-8")); X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PublicKey key = keyFactory.generatePublic(spec);
To convert privatek (string) to a private key:
byte[] keyBytes = Base64.decode(privateK.getBytes("utf-8")); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory fact = KeyFactory.getInstance("RSA"); PrivateKey priv = fact.generatePrivate(keySpec);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码