0
votes

I have a Public key string (128 bytes byte to hex processed) given by my client. I need to generate shared key using the private key and Public key given by client. I'm getting below exception while converting the String to Public key. I tried decoding/encoding the bytes, no improvement. I have the following code.

// This is a sample key.

private static final String PUB_KEY = "0DC1B7102DE3F6785A284ABFCA1822A6B59C947B5F2FAAE" + "672D8EE29C3D801BC153777CD3AF5478FD25C234C50BBABF8CD5215A8F1CB19B0B4A24FD5E9" + "412264646E2A06FCB5929FFBE196A1BD58B9927424C3B3D0388FDDA15FD1FF1C3E7600A629E" + 
"B3F0B38B85CCCE03D44CF8D53B2E4E5EFD54E991CE92E55B10FCCD79F04";

public static void main(String[] argv) throws Exception {   
    PublicKey key = getKey(h2b(PUB_KEY));
}

private static PublicKey getKey(final byte[] pubKey) throws Exception {
    final KeyFactory keyFactory = KeyFactory.getInstance("DH");  
    final X509EncodedKeySpec keySpec = new X509EncodedKeySpec(pubKey);
    return keyFactory.generatePublic(keySpec); // THROWS EXCEPTION
}

private static byte[] h2b(String hex) {
    if ((hex.length() & 0x01) == 0x01)
        throw new IllegalArgumentException();
    byte[] bytes = new byte[hex.length() / 2];
    for (int idx = 0; idx < bytes.length; ++idx) {
        int hi = Character.digit((int) hex.charAt(idx * 2), 16);
        int lo = Character.digit((int) hex.charAt(idx * 2 + 1), 16);
        if ((hi < 0) || (lo < 0))
            throw new IllegalArgumentException();
        bytes[idx] = (byte) ((hi << 4) | lo);
    }
    return bytes;
}

Throws follwoing excetpion. Any help to solve this?

Exception in thread "main" java.security.spec.InvalidKeySpecException: Inappropriate key specification at com.sun.crypto.provider.DHKeyFactory.engineGeneratePublic(DHKeyFactory.java:87)

2
How can a radix-16 digit ever be negative?user207421

2 Answers

0
votes

The X509EncodedKeySpec is expected to contain an array of bytes with the ASN.1 SubjectPublicKeyInfo structure.

The PUB_KEY in your example is probably the raw key value (y in the terms of javax.crypto.spec.DHPublicKeySpec) which is not enough to create the keyspec.

You should ask your client eother for the proper public key in the ASN.1 form to be used as input for X509EncodedKeySpec (this is preferable) or for p and g parameters required for DHPublicKeySpec.

0
votes
  1. Follow 3 steps convert String to DH,DSA publickey or privatekey

Generate Publickey

KeyPair pair = keyPair.generateDHKeyPair();// this will generate public private key
PublicKey publicKey=pair.getPublic();

2:convert publickey to publicKey.getEncoded return byte[].

byte[] byte_pubkey = public_key.getEncoded();
System.out.println("\nBYTE KEY::: " + byte_pubkey);

3://converting byte to String

String pukkey64 = "";
        //byte[] pukkey64 = new byte[0];
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            Base64.Encoder encoder = Base64.getEncoder();
            pukkey64 = encoder.encodeToString(byte_pubkey);
            Log.e("pukkey64", new String(pukkey64));
        } 

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // GenpubKeyFromString(pair2.getPublic().toString());
            try {
                GenpubKeyFromString(pukkey64);
            } catch (GeneralSecurityException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

This Function Generate the publickey or private key whatever you need

@RequiresApi(api = Build.VERSION_CODES.O)
    void GenpubKeyFromString(String pubKey) throws GeneralSecurityException, UnsupportedEncodingException {
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] publicKeyBytes=decoder.decode(pubKey);
        KeyFactory kf = KeyFactory.getInstance("DH");
        PublicKey publicKey = kf.generatePublic(new X509EncodedKeySpec(publicKeyBytes));
        Log.e("publicKey String", publicKey.toString());
        
    }

// convert string to privatekey

public static PrivateKey GetPrivateKeyFromString(String priKey) throws GeneralSecurityException, UnsupportedEncodingException {
        byte[] decodedKey = Base64.decode(priKey, Base64.NO_WRAP);
        KeyFactory kf = KeyFactory.getInstance("DH");
        PrivateKey privateKey = kf.generatePrivate(new PKCS8EncodedKeySpec(decodedKey));
        return privateKey;
    }