尝试使用RSA私钥加密时,Android应用程序中出现InvalidKeyException

尝试使用RSA私钥加密时,Android应用程序中出现InvalidKeyException,android,encryption,keystore,android-keystore,key-pair,Android,Encryption,Keystore,Android Keystore,Key Pair,我正试图用硬件支持的密钥库中生成的密钥对在我的Android应用程序中进行加密/解密。以下是我的密钥生成代码: public void createKeys() { Context ctx = getApplicationContext(); Calendar start = new GregorianCalendar(); Calendar end = new GregorianCalendar(); end.add(Calendar.YEAR, 1);

我正试图用硬件支持的密钥库中生成的密钥对在我的Android应用程序中进行加密/解密。以下是我的密钥生成代码:

public void createKeys() {
    Context ctx = getApplicationContext();
    Calendar start = new GregorianCalendar();
    Calendar end = new GregorianCalendar();
    end.add(Calendar.YEAR, 1);
    try {
        KeyPairGenerator kpGenerator = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
        AlgorithmParameterSpec spec = null;

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR1 && Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            spec = new KeyPairGeneratorSpec.Builder(ctx)
                    .setAlias(mAlias)
                    .setSubject(new X500Principal("CN=" + mAlias))
                    .setSerialNumber(BigInteger.valueOf(1337))
                    .setStartDate(start.getTime())
                    .setEndDate(end.getTime())
                    .build();
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            spec = new KeyGenParameterSpec.Builder(mAlias,
                    KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                    .setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512)
                    .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1)
                    .build();
        }
        kpGenerator.initialize(spec);
        KeyPair kp = kpGenerator.generateKeyPair();
    } catch (NoSuchAlgorithmException e) {
        Log.w(TAG, "RSA not supported", e);
    } catch (NoSuchProviderException e) {
        Log.w(TAG, "No such provider: AndroidKeyStore");
    } catch (InvalidAlgorithmParameterException e) {
        Log.w(TAG, "No such provider: AndroidKeyStore");
    }
}
public String encrypt(String challenge) {
    try {
        KeyStore mKeyStore = KeyStore.getInstance("AndroidKeyStore");
        mKeyStore.load(null);
        KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry) mKeyStore.getEntry(mAlias, null);
        Cipher cip = null;
        cip = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cip.init(Cipher.ENCRYPT_MODE, entry.getPrivateKey());
        byte[] encryptBytes = cip.doFinal(challenge.getBytes());
        String encryptedStr64 = Base64.encodeToString(encryptBytes, Base64.NO_WRAP);
        return encryptedStr64;
    } catch (NoSuchAlgorithmException e) {
        Log.w(TAG, "No Such Algorithm Exception");
        e.printStackTrace();
    } catch (UnrecoverableEntryException e) {
        Log.w(TAG, "Unrecoverable Entry Exception");
        e.printStackTrace();
    } catch (KeyStoreException e) {
        Log.w(TAG, "KeyStore Exception");
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        Log.w(TAG, "Invalid Key Exception");
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
        Log.w(TAG, "No Such Padding Exception");
        e.printStackTrace();
    } catch (BadPaddingException e) {
        Log.w(TAG, "Bad Padding Exception");
        e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
        Log.w(TAG, "Illegal Block Size Exception");
        e.printStackTrace();
    } catch (CertificateException e) {
        Log.w(TAG, "Certificate Exception");
    } catch (IOException e) {
        Log.w(TAG, "IO Exception", e);
    }
    return null;
}
密钥生成成功完成。我还使用KeyInfo.isInsideSecureHardware()验证它是否有硬件支持。但是,我在ENCRYPT()中的cip.init(Cipher.ENCRYPT_MODE,entry.getPrivateKey())行上不断得到InvalidKeyException。确切的例外是

java.security.InvalidKeyException: Keystore operation failed

有人知道原因吗?

只有在使用公钥时,加密才有意义。如果你用私钥“加密”,那么你实际上是在创建一个签名。Java/Android对此有一个单独的类。

只有在使用公钥时,加密才有意义。如果你用私钥“加密”,那么你实际上是在创建一个签名。Java/Android对此有一个单独的类。

好的,所以我尝试用私钥签名,但仍然出现无效密钥异常:密钥库操作失败。Android中有RSA签名/验证的示例代码吗?那么,您解决了吗?你可以用一些代码添加你自己的答案。哦,是的,我添加了。你的回答是正确的。我的印象是我可以用私钥加密,因为github中有一个示例代码可以做到这一点。显然它不起作用。好的,所以我尝试用私钥代替签名,但仍然得到无效密钥异常:密钥库操作失败。Android中有RSA签名/验证的示例代码吗?那么,您解决了吗?你可以用一些代码添加你自己的答案。哦,是的,我添加了。你的回答是正确的。我的印象是我可以用私钥加密,因为github中有一个示例代码可以做到这一点。显然它不起作用。