需要从y,p,g创建DHPublicKey作为BigIntegers

时间:2013-12-09 17:06:22

标签: java public-key-encryption diffie-hellman

我需要一个DHPublicKey来加密一些数据。 因此,我获得了所有需要的参数,如BigIntegers(y,p,g)。 不幸的是,我没有看到从这些适合DHPublicKey接口的参数创建公钥对象的直接方法。 有什么想法吗?

1 个答案:

答案 0 :(得分:2)

    KeyFactory keyFactory;
    KeyPairGenerator kpg;
    DHPublicKey originalDhPubKey, fromSpecsDhPubKey;
    DHPublicKeySpec dhPubKeySpecs;
    KeyPair kp;
    BigInteger p, g, y;

    // generate a DH key pair
    kpg = KeyPairGenerator.getInstance("DH");
    kp = kpg.generateKeyPair();

    // get the DH public key
    originalDhPubKey = (DHPublicKey) kp.getPublic();
    // get P, G and Y specs
    p = originalDhPubKey.getParams().getP();
    g = originalDhPubKey.getParams().getG();
    y = originalDhPubKey.getY();

    // get a DH KeyFactory
    keyFactory = KeyFactory.getInstance("DH");

    // create a DHPublicKeySpec with the specs you have
    dhPubKeySpecs = new DHPublicKeySpec(y, p, g);

    // get the DHPublicKey
    fromSpecsDhPubKey = (DHPublicKey) keyFactory.generatePublic(dhPubKeySpecs);

    // Check that the DH public values are equal
    System.out.println(originalDhPubKey.getY().equals(fromSpecsDhPubKey.getY()));