谈谈从key material还原出key

    首先,我遇到的问题是如何还原出公钥,具体是ECDH的公钥,开始踩进了通过key material计算出ECPoint的x和y参数后,构造出ECPoint w  = new ECPoint(x, y);加上ECParameterSpec作为参数在经由ECPublicKeySpec令到keyFactory能够generatePublic,但是蛋疼的是怎么算都还原不出正确的key。然后果断采取以下方法解决问题得意


有码为证!直接上方法:


    public static XXXPublicKey decodeXXXPublicKey(byte[] pkBytes) {
        X509EncodedKeySpec ks = new X509EncodedKeySpec(pkBytes);
        KeyFactory kf;
        try {
             kf = KeyFactory.getInstance("XXX","PROVIDER");
        } catch (NoSuchAlgorithmException e) {
            log.error("Cryptography error: could not initialize XXX keyfactory!", e);
            return null;
        }
        XXXPublicKey remotePublicKey;
        try {
            remotePublicKey = (XXXPublicKey)kf.generatePublic(ks);
            return remotePublicKey;
        } catch (InvalidKeySpecException e) {
            log.warn("Received invalid key specification from client",e);
            return null;
        } catch (ClassCastException e) {
            log.warn("Received valid X.509 key from client but it was not XXX Public Key material",e);
            return null;
        } 
    }

然后,我们来谈谈人生,咳咳。。谈谈重点:

通常,不管是非对称加密的公钥也好,还是对称加密的密钥也好,都会在通信的时候进行序列化以便传输,当对方收到后进行解密的时候就需要通过这个Key material来还原成对象以便后续解密过程。

在还原公钥中,我们可以Creates a new X509EncodedKeySpec with the given encoded key.

在还原私钥中,我们可以Creates a new PKCS8EncodedKeySpec with the given encoded key.

然后,以上二者继承的EncodedKeySpec是represents a public or private key in encoded format.

EncodedKeySpec又继承自KeySpec接口[A (transparent) specification of the key material that constitutes a cryptographic key.]

(原谅我懒的给你们画uml了 Orz)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章