The two strings that are the private and public keys are :
static String Public = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDH+wPrKYG1KVlzQUVtBghR8n9d" + "/n" + "zcShSZo0+3KgyVdOea7Ei7vQ1U4wRn1zlI5rSqHDzFitblmqnB2anzVvdQxLQ3Uq" + "/n" + "EBKBfMihnLgCSW8Xf7MCH+DSGHNvBg2xSNhcfEmnbLPLnbuz4ySn1UB0lH2eqxy5" + "/n"+ "0zstxhTY0binD9Y+rwIDAQAB"+ "/n"; static String Private = "MIICxjBABgkqhkiG9w0BBQ0wMzAbBgkqhkiG9w0BBQwwDgQIr5NQ/LYPG/UCAggA" +"/n"+ "MBQGCCqGSIb3DQMHBAiLh89iGSkmoASCAoBCpAo9/IzDE3yGhvWr9RgozE7revOo" +"/n"+ "V2OXmU+d0+WYAAx2GYVaUCbFVrmgiVmrbiTgLUMXAGIpvxQ2rzyIvRHW/RN3Gcky" +"/n"+ "qR/AwBatzixqrnoS4aD1/Ovjr4hwde4XHYbPEilZZuVAJFiznhy73qm/So4XghSY........." ; I have read the other questions and tried their solutions but nothing worked....I have a public and private key both as strings.. I need to convert them to 'Key' but i keep getting java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException ..at generatePublic and generatePrivate functions.. also the keys are just for testing therefore, it is ok if they are known to others...
public static Key loadPublicKey(String stored) throws GeneralSecurityException, IOException { byte[] data = Base64.getDecoder().decode((stored.getBytes())); X509EncodedKeySpec spec = new X509EncodedKeySpec(data); KeyFactory fact = KeyFactory.getInstance("RSA"); return fact.generatePublic(spec); } public static Key loadPrivateKey(String key64) throws GeneralSecurityException, IOException { byte[] clear = Base64.getDecoder().decode(key64.getBytes()); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(clear); KeyFactory fact = KeyFactory.getInstance("RSA"); PrivateKey priv = fact.generatePrivate(keySpec); Arrays.fill(clear, (byte) 0); return priv; }
+ "/n"\n, not/n. In a string, this would look like"\\n"./n, yourPublicis indeed base64 of X.509-SPKI publickey suitable for JavaX509EncodedKeySpec, but yourPrivateis (base64 of beginning of) an encrypted PKCS8 private key (EncryptedPrivateKeyInfo) whilePKCS8EncodedKeySpecmust be unencrypted or here decrypted. If you have the password and (can) use BouncyCastle see stackoverflow.com/questions/49932334/… otherwise it's rather complicated.