RSA解密错误?

时间:2018-05-17 14:50:20

标签: android encryption rsa

我尝试获取一对密钥(公共和私有)来加密/解密文本。 对于加密没问题。对于解密我从一天起就错了,我不明白为什么。

这是代码的相关部分:

    static void createKey(Context context) {
    try {
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
        Calendar start = Calendar.getInstance(Locale.ITALIAN);
        Calendar end = Calendar.getInstance(Locale.ITALIAN);
        end.add(Calendar.YEAR, 10);
        AlgorithmParameterSpec spec = null;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            spec = new KeyPairGeneratorSpec.Builder(context)
                    .setAlias(BuildConfig.APPLICATION_ID)
                    .setSubject(new X500Principal("CN=Sample Name, O=Android Authority"))
                    .setSerialNumber(BigInteger.ONE)
                    //.setStartDate(start.getTime())
                    //.setEndDate(end.getTime())
                    .build();
        } else {
            spec = new KeyGenParameterSpec.Builder(BuildConfig.APPLICATION_ID,KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                    .setCertificateSubject(new X500Principal("CN=Sample Name, O=Android Authority"))
                    .setDigests(KeyProperties.DIGEST_SHA256)
                    .setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1)
                    .setCertificateSerialNumber(BigInteger.valueOf(1337))
                    .setCertificateNotBefore(start.getTime())
                    .setCertificateNotAfter(end.getTime())
                    .setRandomizedEncryptionRequired(false)
                    .build();
        }
        kpg.initialize(spec);
        KeyPair kp = kpg.generateKeyPair();
        // END_INCLUDE(create_spec)
        Log.d(TAG, "createKey Public Key is: " + kp.getPublic());
        Log.d(TAG, "createKey Private Key is: " + kp.getPrivate());
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (NoSuchProviderException e) {
        e.printStackTrace();
    } catch (InvalidAlgorithmParameterException e) {
        e.printStackTrace();
    }
}


public static String encrypt(Context context, String text) {
    if(text == null || text.isEmpty()) {
        return null;
    }
    KeyStore keyStore = null;
    try {
        keyStore = KeyStore.getInstance("AndroidKeyStore");
        keyStore.load(null);
        PublicKey publicKey = keyStore.getCertificate(BuildConfig.APPLICATION_ID).getPublicKey();

        Cipher input = getCipher();
        input.init(Cipher.ENCRYPT_MODE, publicKey);//, ivspec);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        CipherOutputStream cipherOutputStream = new CipherOutputStream(
                outputStream, input);
        cipherOutputStream.write(text.getBytes("UTF-8"));
        cipherOutputStream.close();

        byte [] vals = outputStream.toByteArray();
        return Base64.encodeToString(vals, Base64.DEFAULT);
    } catch (Exception e) {
        Log.e(TAG, Log.getStackTraceString(e));
    }
    return null;
}

public static String decrypt(Context context, String encryptedText) {
    KeyStore keyStore = null;
    try {
        keyStore = KeyStore.getInstance("AndroidKeyStore");
        keyStore.load(null);
        KeyStore.Entry entry = keyStore.getEntry(BuildConfig.APPLICATION_ID, null);
        PrivateKey privateKey = ((KeyStore.PrivateKeyEntry) entry).getPrivateKey();
        PublicKey publicKey = keyStore.getCertificate(BuildConfig.APPLICATION_ID).getPublicKey();

        Cipher output = getCipher();
        output.init(Cipher.DECRYPT_MODE, privateKey);//, ivspec);

        CipherInputStream cipherInputStream = new CipherInputStream(
                new ByteArrayInputStream(Base64.decode(encryptedText, Base64.DEFAULT)), output);
        ArrayList<Byte> values = new ArrayList<>();
        int nextByte;
        while ((nextByte = cipherInputStream.read()) != -1) {
            values.add((byte)nextByte);
        }

        byte[] bytes = new byte[values.size()];
        for(int i = 0; i < bytes.length; i++) {
            bytes[i] = values.get(i).byteValue();
        }

        return new String(bytes, 0, bytes.length, "UTF-8");

    } catch (Exception e) {
        Log.e(TAG, Log.getStackTraceString(e));
    }
    return null;
}

static Cipher getCipher() throws Exception {
    return Cipher.getInstance("RSA/ECB/PKCS1Padding");
}

当我调用output.init(Cipher.DECRYPT_MODE,privateKey)时抛出异常;在解密方法中是:

05-17 16:52:02.334 31384-31384/ E/Utils: java.security.InvalidKeyException: Keystore operation failed
    at android.security.KeyStore.getInvalidKeyException(KeyStore.java:733)
    at android.security.KeyStore.getInvalidKeyException(KeyStore.java:754)
    at android.security.keystore.KeyStoreCryptoOperationUtils.getInvalidKeyExceptionForInit(KeyStoreCryptoOperationUtils.java:54)
    at android.security.keystore.KeyStoreCryptoOperationUtils.getExceptionForCipherInit(KeyStoreCryptoOperationUtils.java:89)
    at android.security.keystore.AndroidKeyStoreCipherSpiBase.ensureKeystoreOperationInitialized(AndroidKeyStoreCipherSpiBase.java:265)
    at android.security.keystore.AndroidKeyStoreCipherSpiBase.engineInit(AndroidKeyStoreCipherSpiBase.java:109)
    at javax.crypto.Cipher.tryTransformWithProvider(Cipher.java:2977)
    at javax.crypto.Cipher.tryCombinations(Cipher.java:2884)
    at javax.crypto.Cipher$SpiAndProviderUpdater.updateAndGetSpiAndProvider(Cipher.java:2789)
    at javax.crypto.Cipher.chooseProvider(Cipher.java:956)
    at javax.crypto.Cipher.init(Cipher.java:1199)
    at javax.crypto.Cipher.init(Cipher.java:1143)
    at it.a.b.utils.Utils.decrypt(Utils.java:249)
    at it.a.b.activities.LoginActivity.onCreate(LoginActivity.java:90)
    at android.app.Activity.performCreate(Activity.java:6910)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1123)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2746)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2864)
    at android.app.ActivityThread.-wrap12(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1567)
    at android.os.Handler.dispatchMessage(Handler.java:105)
    at android.os.Looper.loop(Looper.java:156)
    at android.app.ActivityThread.main(ActivityThread.java:6577)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:941)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:831)
 Caused by: android.security.KeyStoreException: -65530
    at android.security.KeyStore.getKeyStoreException(KeyStore.java:672)
    at android.security.KeyStore.getInvalidKeyException(KeyStore.java:754) 
    at android.security.keystore.KeyStoreCryptoOperationUtils.getInvalidKeyExceptionForInit(KeyStoreCryptoOperationUtils.java:54) 
    at android.security.keystore.KeyStoreCryptoOperationUtils.getExceptionForCipherInit(KeyStoreCryptoOperationUtils.java:89) 
    at android.security.keystore.AndroidKeyStoreCipherSpiBase.ensureKeystoreOperationInitialized(AndroidKeyStoreCipherSpiBase.java:265) 
    at android.security.keystore.AndroidKeyStoreCipherSpiBase.engineInit(AndroidKeyStoreCipherSpiBase.java:109) 
    at javax.crypto.Cipher.tryTransformWithProvider(Cipher.java:2977) 
    at javax.crypto.Cipher.tryCombinations(Cipher.java:2884) 
    at javax.crypto.Cipher$SpiAndProviderUpdater.updateAndGetSpiAndProvider(Cipher.java:2789) 
    at javax.crypto.Cipher.chooseProvider(Cipher.java:956) 
    at javax.crypto.Cipher.init(Cipher.java:1199) 
    at javax.crypto.Cipher.init(Cipher.java:1143) 
    at it.a.b.utils.Utils.decrypt(Utils.java:249) 
    at it.a.b.activities.LoginActivity.onCreate(LoginActivity.java:90) 
    at android.app.Activity.performCreate(Activity.java:6910) 
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1123) 
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2746) 
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2864) 
    at android.app.ActivityThread.-wrap12(ActivityThread.java) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1567) 
    at android.os.Handler.dispatchMessage(Handler.java:105) 
    at android.os.Looper.loop(Looper.java:156) 
    at android.app.ActivityThread.main(ActivityThread.java:6577) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:941) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:831) 

你对此有什么想法吗?

1 个答案:

答案 0 :(得分:0)

您似乎每次都创建密钥对。在创建之前尝试检查密钥是否存在

if (!keyStore.containsAlias(ALIAS_RSA)) {
    createKeys();
} else {
    retrieveKeys();
}