Hi I'm a student learning about JAVA Cipher Programming. I'm making a JAVA project that send public keys each other and is using socket. But in socket programming, I can send only string and int. So I send public key from server to client. But client received it for string, not public key. I found KeyFactory method. I used KeyFactory for formatting from string to public key, but i failed. Only what I can see was InvalidKeySpecException. I ask this question because I don't know what is the wrong line.
P.S. I'm sorry, it will be difficult for you to understand this question. I'm not good at English because my native language is not English
below is my source code
public class TestSpace {
public static String bytesToHex(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 2);
@SuppressWarnings("resource")
Formatter formatter = new Formatter(sb);
for (byte b : bytes) {
formatter.format("%02x", b);
}
return sb.toString();
}
public static void main(String[] args) {
try {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024);
KeyPair keyPair = kpg.genKeyPair();
PublicKey pubKey = keyPair.getPublic();
PrivateKey priKey = keyPair.getPrivate();
byte[] publicKeyBytes = pubKey.getEncoded();
byte[] privateKeyBytes = priKey.getEncoded();
System.out.println("original public key : " + bytesToHex(publicKeyBytes));
System.out.println("original private key : " + bytesToHex(privateKeyBytes));
String temp1 = publicKeyBytes.toString();
String temp2 = privateKeyBytes.toString();
System.out.println("byte->string public key : " + temp1);
System.out.println("byte->string private key : " + temp2);
publicKeyBytes = temp1.getBytes();
privateKeyBytes = temp2.getBytes();
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(publicKeyBytes));
priKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes));
publicKeyBytes = pubKey.getEncoded();
privateKeyBytes = priKey.getEncoded();
System.out.println("string->byte public key : " + bytesToHex(publicKeyBytes));
System.out.println("string->byte private key : " + bytesToHex(privateKeyBytes));
}catch( NoSuchAlgorithmException|InvalidKeySpecException e) {
e.printStackTrace();
}
}
}