Java RSA使用私钥加密 - 无效的密钥错误

时间:2015-04-06 17:33:03

标签: java encryption cryptography rsa

我正在尝试从使用带有RSA密码的SHA-256生成的私钥文件中加密一些示例文本。此私钥由Verisign(CA权威机构)生成并传递给我们。

以下是我正在使用的代码:

public class EncryptionUtil {
    public static final String ALGORITHM = "RSA";
    public static final String PRIVATE_KEY_FILE = "C:\\keys\\private.key";
    public static byte[] encrypt(String text, PrivateKey key) {
        byte[] cipherText = null;
        try {
            final Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            cipherText = cipher.doFinal(text.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return cipherText;
    }
    public static void main(String[] args) {
        try {
            final String originalText = "This is a test";
            // Encrypt
            final PrivateKey privateKey = readPrivateKey(new File(
                    PRIVATE_KEY_FILE));
            final byte[] cipherText = encrypt(originalText, privateKey);
            // Printing
            System.out.println("Original: " + originalText);
            System.out.println("Encrypted: " + cipherText.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private static PrivateKey readPrivateKey(File file) throws IOException,
            GeneralSecurityException {
        DataInputStream input = new DataInputStream(new FileInputStream(file));
        try {
            byte[] bytes = new byte[(int) file.length()];
            input.read(bytes);
            KeySpec spec = new PKCS8EncodedKeySpec(bytes);
            try {
                return KeyFactory.getInstance("RSA").generatePrivate(spec);
            } catch (InvalidKeySpecException ex) {
                return KeyFactory.getInstance("DSA").generatePrivate(spec);
            }
        } finally {
            input.close();
        }
    }
}

但在return KeyFactory.getInstance("RSA").generatePrivate(spec);  (以及return KeyFactory.getInstance("DSA").generatePrivate(spec);行)我收到以下错误:

java.security.spec.InvalidKeySpecException: Inappropriate key specification: invalid key format
    at sun.security.provider.DSAKeyFactory.engineGeneratePrivate(DSAKeyFactory.java:156)
    at java.security.KeyFactory.generatePrivate(KeyFactory.java:372)

你知道我错过了吗?

我的私钥如下:

-----BEGIN ENCRYPTED PRIVATE KEY-----
base64 private key
-----END ENCRYPTED PRIVATE KEY-----

所以我尝试解码64字节数组,现在出现以下错误:

java.security.spec.InvalidKeySpecException: Inappropriate key specification: IOException : DER input, Integer tag error
    at sun.security.provider.DSAKeyFactory.engineGeneratePrivate(DSAKeyFactory.java:156)
    at java.security.KeyFactory.generatePrivate(KeyFactory.java:372)

当私钥未加密时,以前的代码可以正常工作。

0 个答案:

没有答案