猿问

为什么ECIES私钥加密 公钥解密就出错,但是公钥加密,私钥解密就正常

//公钥加密 私钥解密

//初始化秘钥
try {
    KeyPairGenerator kp=KeyPairGenerator.getInstance("EC","BC");
    kp.initialize(256,new SecureRandom());
    KeyPair keyPair=kp.generateKeyPair();

    ECPublicKey ecPubKey=(ECPublicKey)keyPair.getPublic();

    ECPrivateKey ecPriKey=(ECPrivateKey)keyPair.getPrivate();

    System.out.println("公钥:"+ Base64.encodeBase64String(ecPubKey.getEncoded()));
    System.out.println("私钥:"+ Base64.encodeBase64String(ecPriKey.getEncoded()));
    //私钥加密,公钥解密:加密
    PKCS8EncodedKeySpec peks=new PKCS8EncodedKeySpec(ecPriKey.getEncoded());
    KeyFactory keyFactory=KeyFactory.getInstance("EC");

    PrivateKey priKey=keyFactory.generatePrivate(peks);
    Cipher cipher=Cipher.getInstance("ECIES","BC");

    cipher.init(Cipher.ENCRYPT_MODE,priKey);
    byte[] result=cipher.doFinal("hello".getBytes());

    System.out.println("私钥加密,公钥解密:加密-----"+Base64.encodeBase64String(result));

    //私钥加密,公钥解密:解密

    X509EncodedKeySpec x509=new X509EncodedKeySpec(ecPubKey.getEncoded());
    keyFactory=KeyFactory.getInstance("EC");
    PublicKey pubKey=keyFactory.generatePublic(x509);
    cipher=Cipher.getInstance("ECIES","BC");
    cipher.init(Cipher.DECRYPT_MODE,pubKey);
    result=cipher.doFinal(result);
    System.out.println("私钥加密,公钥解密:解密"+new String(result));

}


catch (NoSuchAlgorithmException e) {
    e.printStackTrace();
} catch (NoSuchProviderException e) {
    e.printStackTrace();
} catch (InvalidKeySpecException e) {
    e.printStackTrace();
} catch (NoSuchPaddingException e) {
    e.printStackTrace();
} catch (InvalidKeyException e) {
    e.printStackTrace();
} catch (BadPaddingException e) {
    e.printStackTrace();
} catch (IllegalBlockSizeException e) {
    e.printStackTrace();
}

异常信息  java.security.InvalidKeyException: must be passed recipient's public EC key for encryption	at org.bouncycastle.jcajce.provider.asymmetric.ec.IESCipher.engineInit(Unknown Source)	at org.bouncycastle.jcajce.provider.asymmetric.ec.IESCipher.engineInit(Unknown Source)	at java.base/javax.crypto.Cipher.init(Cipher.java:1283)	at java.base/javax.crypto.Cipher.init(Cipher.java:1223)


一人我编程累
浏览 2198回答 0
0回答
随时随地看视频慕课网APP
我要回答