I want to generate 512 bit RSA keypair and then encode my public key as a string. How can I achieve this?
            Asked
            
        
        
            Active
            
        
            Viewed 9.4k times
        
    35
            
            
        - 
                    4**Warning**: RSA 512 bit keys are completely insecure. – Maarten Bodewes Feb 13 '19 at 01:22
1 Answers
55
            For output as Hex-String
import java.security.*;
public class Test {
    public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchProviderException {
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(512);
        byte[] publicKey = keyGen.genKeyPair().getPublic().getEncoded();
        StringBuffer retString = new StringBuffer();
        for (int i = 0; i < publicKey.length; ++i) {
            retString.append(Integer.toHexString(0x0100 + (publicKey[i] & 0x00FF)).substring(1));
        }
        System.out.println(retString);
    }
}
For output as byte values
import java.security.*;
public class Test {
    public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchProviderException {
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(512);
        byte[] publicKey = keyGen.genKeyPair().getPublic().getEncoded();
        StringBuffer retString = new StringBuffer();
        retString.append("[");
        for (int i = 0; i < publicKey.length; ++i) {
            retString.append(publicKey[i]);
            retString.append(", ");
        }
        retString = retString.delete(retString.length()-2,retString.length());
        retString.append("]");
        System.out.println(retString); //e.g. [48, 92, 48, .... , 0, 1]
    }
}
 
    
    
        Sir Wumpus IV
        
- 5
- 3
 
    
    
        jitter
        
- 53,475
- 11
- 111
- 124
- 
                    Thank you very much! If i should get result like this [48, -137, -97, 49, 13, 6, 8, 42, -122, 72, -122, -9, 13, 2, 3, 15 4, 0, 3, -132, -115, 0, 48, -127] should i use just toString method instead retString.append(Integer.toHexString(0x0100 + (publicKey[i] & 0x00FF)).substring(1)); ?? – Angela Nov 10 '09 at 18:54
- 
                    4
- 
                    6to output as HEX the simpler solution is to use `javax.xml.bind.DatatypeConverter.printHexBinary(publicKey)` @YatinGrover for PEM Base 64 you can use `javax.xml.bind.DatatypeConverter.printBase64Binary(publicKey)` – vsapiha May 27 '15 at 12:17
- 
                    Also you can consider org.apache.commons.codec.binary.Hex#encodeHexString as a way to get a hex string from an array of bytes. – Jul 05 '17 at 07:13
 
    