当前位置:  开发笔记 > 编程语言 > 正文

Android解密错误

如何解决《Android解密错误》经验,为你挑选了3个好方法。

我试图在我的Android应用程序中加密和解密字符串但我不断收到InvalidKeyException错误.

这是我的代码:

//生成密钥方法

public void generateKeys() {
    Calendar cal = Calendar.getInstance();
    Date now = cal.getTime();
    cal.add(Calendar.YEAR, 25);
    Date end = cal.getTime();

    KeyPairGenerator kpg = null;
    try {
        kpg = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (NoSuchProviderException e) {
        e.printStackTrace();
    }
    try {
        kpg.initialize(new KeyPairGeneratorSpec.Builder(context)
                .setAlias(KEY_ALIAS)
                .setStartDate(now)
                .setEndDate(end)
                .setSerialNumber(BigInteger.valueOf(1))
                .setSubject(new X500Principal("CN=" + KEY_ALIAS))
                .build());
    } catch (InvalidAlgorithmParameterException e) {
        e.printStackTrace();
    }

    KeyPair kp = kpg.generateKeyPair();

    KeyStore ks = null;
    try {
        ks = KeyStore.getInstance("AndroidKeyStore");
        ks.load(null);
        Enumeration aliases = ks.aliases();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    KeyStore.Entry entry = null;
    try {
        entry = ks.getEntry(KEY_ALIAS, null);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (UnrecoverableEntryException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    }
    if (!(entry instanceof KeyStore.PrivateKeyEntry)) {
        Log.e(LOG_TAG, "Not an instance of PrivateKeyEntry.");
    }
    else{
        privKey = ((KeyStore.PrivateKeyEntry) entry).getPrivateKey();
        pubKey = ((KeyStore.PrivateKeyEntry) entry).getCertificate().getPublicKey();
    }

}

//加密方法

private String encryptString(String value){
    byte[] encodedBytes = null;
    try {
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "AndroidOpenSSL");
        cipher.init(Cipher.ENCRYPT_MODE,  pubKey);
        encodedBytes = cipher.doFinal(value.getBytes());
    } catch (Exception e) {
        e.printStackTrace();
    }

    return Base64.encodeToString(encodedBytes, Base64.DEFAULT);
}

//解密方法

private String decryptString(String value){
    byte[] decodedBytes = null;
    try {
        Cipher c = Cipher.getInstance("RSA/ECB/PKCS1Padding", "AndroidOpenSSL");
        c.init(Cipher.DECRYPT_MODE,  privKey);
        decodedBytes = c.doFinal(Base64.decode(value, Base64.DEFAULT));
    } catch (Exception e) {
        e.printStackTrace();
        Log.e("Error", "Error = " + e);
        return "SECURE_FAILURE";
    }

    return new String(decodedBytes);
}

//测试代码

    generateKeys();
    String encrypted = encryptString("Hello World");
    Log.e("Encrypt", "encrypted = " + encrypted);
    String decrypted = decryptString(encrypted);
    Log.e("Decrypt", "decrypted = " + decrypted);

看起来加密工作正常,因为它打印出这样的东西:

加密= SbA2iWWKQbDL7NTA9xvtjD/viYDdpx9fLRYTSZ8UQzdBy3QLqzkswBY21ErH7FPza3vZys4E4PZw uxaGkRz0aC0FLqsYlbpcJernGm5 + D5lRcBOaZmgkNY9pMf0YP75cBbcJdcmb1rDaH40nCRDnEoXv rGESJRqT6p0NMzlZqdd9KO3tqfExwgservAWxPNtRDBbMgE4I/09418jM5Ock5eayfOuv/STwEy6 Ecd56UjFH63h + gP6ed2aMDhBVeExMxvdloY + VnsAxS5Dkoc2GdaljtjRuPK48HQASoJK8EwAMNpz

但是当我尝试解密时,我收到以下错误:

java.security.InvalidKeyException:需要RSA私钥或公钥

我无法理解为什么我会得到这个例外?有人可以帮忙吗?



1> 小智..:

这对我有用:

private Cipher getCipher() {
    try {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { // below android m
            return Cipher.getInstance("RSA/ECB/PKCS1Padding", "AndroidOpenSSL"); // error in android 6: InvalidKeyException: Need RSA private or public key
        }
        else { // android m and above
            return Cipher.getInstance("RSA/ECB/PKCS1Padding", "AndroidKeyStoreBCWorkaround"); // error in android 5: NoSuchProviderException: Provider not available: AndroidKeyStoreBCWorkaround
        }
    } catch(Exception exception) {
        throw new RuntimeException("getCipher: Failed to get an instance of Cipher", exception);
    }
}


嗯...如果我们在Lollipop上创建了公共和私有RSA密钥,然后用户将他的Android操作系统升级到了棉花糖,该怎么办?而且我们的方法将返回不同的提供程序-它将与以前生成的RSA密钥一起使用吗?

2> Luis..:

尝试使用其他提供商,如下所示:

Cipher.getInstance("RSA/ECB/PKCS1Padding", "AndroidKeyStoreBCWorkaround");


适合我,虽然一些解释会很棒.

3> 小智..:

删除提供程序对我有用:

Cipher.getInstance("RSA/ECB/PKCS1Padding")

来自Java文档:"此方法遍历已注册的安全提供程序列表,从最首选的提供程序开始.将返回一个新的Cipher对象,该对象将封装来自第一个支持指定算法的提供程序的CipherSpi实现."

推荐阅读
k78283381
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有