Need to create DHPublicKey from y, p, g as BigIntegers

你说的曾经没有我的故事 提交于 2019-12-08 04:18:04

问题


I need a DHPublicKey to encrypt some data. Therefore I have been provided with all the needed parameters as BigIntegers (y, p, g). Unfortunately I don't see a straight way for creating a public key object from these parameters that would fit the DHPublicKey interface. Any idea?


回答1:


    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()));


来源:https://stackoverflow.com/questions/20476365/need-to-create-dhpublickey-from-y-p-g-as-bigintegers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!