0

I'm trying to save an RSA key pair (Public/Private) into a database in a String format and then retrieve them from the database and convert them back into (Public key/ Private key) format.

I tried the following code; the first function generates the public/private code and the last two functions is for converting a string to a key pair format.

    public static Voter generateKeyPair(Voter v) throws NoSuchAlgorithmException {
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA");
    kpg.initialize(2048, new SecureRandom(v.getPassword().getBytes()));
    KeyPair kp = kpg.generateKeyPair();
    PrivateKey privKey = kp.getPrivate();
    PublicKey pubKey = kp.getPublic();
    String pubKeyString = new BigInteger(pubKey.getEncoded()).toString(64);
    String privKeyString = new BigInteger(privKey.getEncoded()).toString(64);
    v.setPrivateKey(privKeyString);
    v.setPublicKey(pubKeyString);
    return v;
    }

public static Key getPublicKey(String keyString) throws GeneralSecurityException, IOException {
    byte[] key = Base64.getDecoder().decode((keyString.getBytes()));
    X509EncodedKeySpec spec = new X509EncodedKeySpec(key);
    KeyFactory fact = KeyFactory.getInstance("DSA");
    PublicKey pub = fact.generatePublic(spec);
    return pub;
}

public static Key getPrivateKey(String keyString) throws GeneralSecurityException, IOException {
    byte[] key = Base64.getDecoder().decode(keyString.getBytes());
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(key);
    KeyFactory fact = KeyFactory.getInstance("DSA");
    PrivateKey priv = fact.generatePrivate(keySpec);
    return priv;

}

First thing, I got the value for the public key > private key which doesn't make sense.

When I try to run the code I get the following error: java.security.spec.InvalidKeySpecException: Inappropriate key specification: IOException: DerInputStream.getLength(): lengthTag=13, too big.

Ahmed
  • 1

0 Answers0