简体   繁体   中英

Converting string to key and vice versa

I have problem with converting Key (security) to string and next convert it to that object. I have some errors:

java.lang.IllegalArgumentException: Illegal base64 character 20

and my code:

KeyPairGenerator kpairg = KeyPairGenerator.getInstance("RSA");
kpairg.initialize(1024);
KeyPair kpair = kpairg.genKeyPair();
Key publicKey = kpair.getPublic();

// to String
String textFromKey = Base64.getEncoder().encodeToString(publicKey.getEncoded());

// to Key
byte[] byteKey = Base64.getDecoder().decode(textFromKey.getBytes());
X509EncodedKeySpec X509publicKey = new X509EncodedKeySpec(byteKey);
KeyFactory kf = KeyFactory.getInstance("RSA");
Key pubb = kf.generatePublic(X509publicKey);

textFromKey is sending to UDP server textFromKey is a output from server if I want to use that key I saw some answers in that website but anything help me. Could you look at this?

IDE told me that there is a problem: byte[] byteKey = Base64.getDecoder().decode(textFromKey.getBytes());

The issue is not clear from just the code. Can you try doing just

X509EncodedKeySpec X509publicKey = new X509EncodedKeySpec(publicKey.getEncoded());

and get back?

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