首先,我遇到的問題是如何還原出公鑰,具體是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)