当前位置: 首页 > 知识库问答 >
问题:

RSA解密错误?

梁丘安晏
2023-03-14

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

这是代码的相关部分:

    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");
}
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个答案

支铭晨
2023-03-14

好像你每次都在创建密钥对。尝试在创建密钥之前检查它们是否存在

if (!keyStore.containsAlias(ALIAS_RSA)) {
    createKeys();
} else {
    retrieveKeys();
}
 类似资料:
  • 本章是前一章的延续,我们使用RSA算法逐步实现加密,并详细讨论它。 用于解密密文的函数如下 - def decrypt(ciphertext, priv_key): cipher = PKCS1_OAEP.new(priv_key) return cipher.decrypt(ciphertext) 对于公钥加密或非对称密钥加密,重要的是保持两个重要的功能,即Authenticati

  • 我当前在解密服务器上的RSA加密数据时遇到了问题,服务器使用Node.js并使用node-rsa库进行加密/解密。 在我的Android客户端上没有任何问题地接收到公钥,但是当尝试解密数据时,我得到了以下异常: 这就是我在客户端上生成公钥的方式 以下是客户端的加密:

  • 我们封装了一个RSA 加解密的工具放在 extends 中。首先看看它的文件结构 rsa |-- RSACrypt 加解密主程序 |-- RSACryptBigData 大数据加解密 |-- SignUtil 签名类 |-- rsa_public_key.pem 公钥 |-- rsa_private_key.pem 私钥 RSACrypt API RSAC

  • 请帮助我识别以下RSA加密代码中的问题

  • 我有一个没有Java加密库的RSA代码类。很管用。 但是,当我从RSAPrivateKeySpec创建一个Java库PrivateKey,从类中的RSAPrivateKey创建一个模数和指数,并使用Java加密库a使用类encrypted BigInteger进行加密时,它会抛出。这里: 为什么? 对不起,我的英语不好

  • 在一个做其他事情的大型应用程序中——我需要加密和解密一个文件。所以我一直在四处寻找,并实现了这两个核心功能,基本上使用RSA密钥包装一个随机的AES密钥来加密一个文件。对称键和iv被写入文件的开头。 我在下面的解密函数部分得到一个异常(“javax.crypto.BadPaddingException:Decryption error”)。在肯安迪夫线路上——doFinal。具体来说,这一行是异常