Emad
Emad

Reputation: 91

generate public and private Keys in Hexadecimal in Java

I want to generate the public and the private key in Hexadecimal. The current output is written in Chinese language. I want the output of public and private key written in Hexadecimal.

// Class
public class GenerateKeys {

private final KeyPairGenerator keyGen;
private KeyPair pair;
private PrivateKey privateKey;
private PublicKey publicKey;

// Constructor
public GenerateKeys(int keylength) throws NoSuchAlgorithmException, NoSuchProviderException {
    this.keyGen = KeyPairGenerator.getInstance("RSA"); // Algorithm 
    this.keyGen.initialize(keylength);
    }

public void createKeys() {
    this.pair = this.keyGen.generateKeyPair();
    this.privateKey = pair.getPrivate();
    this.publicKey = pair.getPublic();
}

public PrivateKey getPrivateKey() {
    return this.privateKey;
}

public PublicKey getPublicKey() {
    return this.publicKey;
}

public void writeToFile(String path, byte[] key) throws IOException {
    File f = new File(path);
    f.getParentFile().mkdirs();

        try (FileOutputStream fos = new FileOutputStream(f)) {
            fos.write(key);
            fos.flush();
        }
    }
    // Main
    public static void main(String[] args)
    {
        GenerateKeys gk;
        try {
            gk = new GenerateKeys(1024);
            gk.createKeys();
            gk.writeToFile("MyKeys/publicKey",gk.getPublicKey().getEncoded());
            gk.writeToFile("MyKeys/privateKey",gk.getPrivateKey().getEncoded());
        } catch (NoSuchAlgorithmException | NoSuchProviderException | IOException e) {
            System.err.println(e.getMessage());
        }
    }
}

Upvotes: 0

Views: 1608

Answers (1)

LuminousNutria
LuminousNutria

Reputation: 2001

It doesn't seem like you are actually creating a file written in the Chinese language. What you seem to be doing is creating what's called a "binary" file. These are files that your computer can understand, but when you open them in a text editor, you can't read them because they don't make any sense. Symbols from other languages will often appear.

Writing byte[] arrays with FileOutputStream will always make a binary file.

To create a file that's readable by humans and displays your keys in hexadecimal you can replace your writeToFile() method with this code.

public void writeToFile(String path, byte[] key) throws IOException {
    File f = new File(path);
    f.getParentFile().mkdirs();

    StringBuilder sb = new StringBuilder();
    for(byte b: key) {
        sb.append(String.format("%02X", b) + " ");
    }

    try (FileWriter fos = new FileWriter(f)) {
        fos.write(sb.toString());
        fos.flush();
    }
}

This should generate a text file with each key value in your byte[] array converted to hexadecimal.

Upvotes: 4

Related Questions