异常java.security.InvalidKeyException:尝试加载.openssl和.pkcs8密钥时无效的密钥格式

时间:2016-12-14 06:44:18

标签: java encryption openssl axis2

在开发轴客户端时,我需要使用publickey.openssl加密String,并使用从本地machine.thanks加载的privatekey.pkcs8进行解密。

运行代码我得到以下异常;

      java.security.spec.InvalidKeySpecException:      java.security.InvalidKeyException: invalid key format
    at sun.security.rsa.RSAKeyFactory.engineGeneratePublic(Unknown Source)
    at java.security.KeyFactory.generatePublic(Unknown Source)
    at client.client.readPublicKey(client.java:69)
    at client.client.main(client.java:97)
Caused by: java.security.InvalidKeyException: invalid key format
    at sun.security.x509.X509Key.decode(Unknown Source)
    at sun.security.x509.X509Key.decode(Unknown Source)
    at sun.security.rsa.RSAPublicKeyImpl.<init>(Unknown Source)
    at sun.security.rsa.RSAKeyFactory.generatePublic(Unknown Source)
    ... 4 more

我正在使用的代码:

public static byte[] readFileBytes(String filename) throws IOException
{
    Path path = Paths.get(filename);
    return Files.readAllBytes(path);        
}
  public static PublicKey readPublicKey(String filename) throws     IOException,NoSuchAlgorithmException,InvalidKeySpecException
{
    X509EncodedKeySpec publicSpec = new X509EncodedKeySpec(readFileBytes(filename));
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");


    return keyFactory.generatePublic(publicSpec);
}
public static PrivateKey readPrivateKey(String filename) throws IOException,NoSuchAlgorithmException,InvalidKeySpecException
{
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(readFileBytes(filename));
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    return keyFactory.generatePrivate(keySpec);
}
public static byte[] encrypt(PublicKey key,byte[] plaintext) throws NoSuchAlgorithmException,NoSuchPaddingException,InvalidKeySpecException,IllegalBlockSizeException,BadPaddingException, InvalidKeyException
{
    Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding");
    cipher.init(Cipher.ENCRYPT_MODE,key);
    return cipher.doFinal(plaintext);
}
public static byte[] decrypt(PrivateKey key,byte[] ciphertext)throws NoSuchAlgorithmException,NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException
{
    Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding");
    cipher.init(Cipher.DECRYPT_MODE,key);
    return cipher.doFinal(ciphertext);

}

并提供路径和加密解密:

 PublicKey publicKey = readPublicKey("C:\\publickey.openssl");
        PrivateKey privateKey = readPrivateKey("C:\\privatekey.pkcs8");
        byte[] message = "11111111111111111|10:22:30".getBytes("UTF8");
        byte[] secret = encrypt(publicKey,message);
        byte[] recovered_message = decrypt(privateKey,secret);
        System.out.println(new String(recovered_message,"UTF8"));

0 个答案:

没有答案