java.lang.IllegalArgumentException:解密字符串时bad base-64

时间:2016-12-06 03:38:45

标签: encryption android-keystore

我正在尝试使用KeyStore加密字符串,并将此帖子用作参考。

KeyPairGeneratorSpec replacement with KeyGenParameterSpec.Builder equivalents - Keystore operation failed

然而,我一直得到这个"坏基地-64"当我解密字符串。我不知道如何解决这个问题。我知道加密的字符串包含解密器不知道的字符。但我不理解修复。

我看到了一些这样的帖子,但由于答案上没有代码,所以没有多大帮助。

java.lang.IllegalArgumentException: bad base-64

这是我的测试代码的剪辑,有人可以告诉我如何删除我的字符串吗?

Cipher inCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "AndroidOpenSSL");
inCipher.init(Cipher.ENCRYPT_MODE, publicKey);

Cipher outCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "AndroidOpenSSL");
outCipher.init(Cipher.DECRYPT_MODE, privateKey);

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

String ecryptedText = outputStream.toString();
Log.d(TAG, "Encrypt = " + ecryptedText);

String cipherText = ecryptedText;
CipherInputStream cipherInputStream = new CipherInputStream(
        new ByteArrayInputStream(Base64.decode(cipherText, Base64.DEFAULT)), outCipher);
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();
}

String finalText = new String(bytes, 0, bytes.length, "UTF-8");
Log.d(TAG, "Decrypt = " + ecryptedText);

1 个答案:

答案 0 :(得分:1)

以下是一个有关如何使用 Android <?php <meta http-equiv="refresh" content="0;URL=contact2.html" / // configure $from = 'Demo contact form <Contact@gmail.com>'; $sendTo = 'Demo contact form <tomwilkinson104@gmail.com>'; $subject = 'New message from contact form'; $fields = array('name' => 'Name', 'surname' => 'Surname', 'email' => 'Email', 'message' => 'Message'); // array variable name => Text to appear in email $okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!'; $errorMessage = 'There was an error while submitting the form. Please try again later'; //sending try { $emailText = "You have new message from contact form\n=============================\n"; foreach ($_POST as $key => $value) { if (isset($fields[$key])) { $emailText .= "$fields[$key]: $value\n"; } } mail($sendTo, $subject, $emailText, "From: " . $from); $responseArray = array('type' => 'success', 'message' => $okMessage); } catch (\Exception $e) { $responseArray = array('type' => 'danger', 'message' => $errorMessage); } if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') { $encoded = json_encode($responseArray); header('Content-Type: application/json'); echo $encoded; } else { echo $responseArray['message']; } 使用KeyStoreByteArrayOutputStream加密/解密内存字符串的工作示例。请注意提供商更改,ByteArrayInputStream使用>= 6,旧版本使用"AndroidKeyStoreBCWorkaround"。此外,您必须使用"AndroidOpenSSL"将加密数据编码为Base64字符串,如下所示:

Base64.encodeToString

我的最终工作示例基于您的代码

String ecryptedText = Base64.encodeToString(outputStream.toByteArray(), Base64.DEFAULT);

<强> OUTPUTS

try {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(
            KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore");
    keyPairGenerator.initialize(
            new KeyGenParameterSpec.Builder(
                    "key1",
                    KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                    .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1)
                    .build());
    KeyPair keyPair = keyPairGenerator.generateKeyPair();

    // error in android 6: InvalidKeyException: Need RSA private or public key AndroidOpenSSL
    // error in android 5: NoSuchProviderException: Provider not available: AndroidKeyStoreBCWorkaround
    String provider = Build.VERSION.SDK_INT < Build.VERSION_CODES.M ? "AndroidOpenSSL" : "AndroidKeyStoreBCWorkaround";

    Cipher inCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", provider);
    inCipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());

    Cipher outCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", provider);
    outCipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    CipherOutputStream cipherOutputStream = new CipherOutputStream(
            outputStream, inCipher);

    String plainText = "This is a text";

    cipherOutputStream.write(plainText.getBytes("UTF-8"));
    cipherOutputStream.close();

    String ecryptedText = Base64.encodeToString(outputStream.toByteArray(), Base64.DEFAULT);
    Log.d(TAG, "Encrypt = " + ecryptedText);

    String cipherText = ecryptedText;
    CipherInputStream cipherInputStream = new CipherInputStream(
            new ByteArrayInputStream(Base64.decode(cipherText, Base64.DEFAULT)), outCipher);

    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();
    }

    String finalText = new String(bytes, 0, bytes.length, "UTF-8");
    Log.d(TAG, "Decrypt = " + finalText);
} catch (javax.crypto.NoSuchPaddingException e) {
    Log.e(TAG, Log.getStackTraceString(e));
} catch (IOException e) {
    Log.e(TAG, Log.getStackTraceString(e));
} catch (NoSuchAlgorithmException e) {
    Log.e(TAG, Log.getStackTraceString(e));
} catch (NoSuchProviderException e) {
    Log.e(TAG, Log.getStackTraceString(e));
} catch (InvalidAlgorithmParameterException e) {
    Log.e(TAG, Log.getStackTraceString(e));
} catch (InvalidKeyException e) {
    Log.e(TAG, Log.getStackTraceString(e));
} catch (UnsupportedOperationException e) {
    Log.e(TAG, Log.getStackTraceString(e));
}

Android Studio Output

<强>更新

对于 Android API 19 ,您只需使用之前的 KeyStore API D/MainActivity: Encrypt = rejkfeas3HgYnZOlC4S/R3KvlMTyiBjr5T6LqWGj9bq6nvpM0KBsoeYtr4OdCLITFX5GojuO4VpB Hy11n8zc9JcAx4IFW0Aw0/DfCmMDvIomQItBAaIWewZqNHc0UwS0y/JRhAe8SiTz5sFJ6Abvgax6 vEfbYT0gzok+qtlfBNQLPvXejquhc0pZBaX1RgKDZyEJh3DBVRaFDgogK8XphaI/xtd1Cww9uO63 QxA7HfrFUN8rJXrHF4EMi/yrDxs2xVHGF0v21xeuXRwLW9JXYn4fFAJJ0Jr8N5f03UDuKeNlI568 RFVOGH7WpOLvKN4CDlsC+DT4Z8YVIOdtS/tO+Q== D/MainActivity: Decrypt = This is a text 而不是KeyPairGeneratorSpec,如下所示:

KeyGenParameterSpec