谈谈从key material还原出key

来源:互联网 发布:张国荣告别演唱会知乎 编辑:程序博客网 时间:2024/05/22 08:13

    首先,我遇到的问题是如何还原出公钥,具体是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)

0 0