2016-12-06 76 views
3

我試圖使用KeyStore加密一個字符串並將此帖用作參考。java.lang.IllegalArgumentException:解密字符串時的base-64錯誤

KeyPairGeneratorSpec replacement with KeyGenParameterSpec.Builder equivalents - Keystore operation failed

然而,我一直當我解密字符串獲得這個 「壞基地-64」。我不知道如何解決這個問題。我知道加密的字符串包含解密者不知道的字符。但我不明白這個問題。

我看到一些類似的帖子,但沒有太大幫助,因爲答案上沒有代碼。

java.lang.IllegalArgumentException: bad base-64

這是一個剪斷我的測試代碼,可以有人告訴我,我怎麼decrpyt我的字符串?

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); 
+0

50分誰可以粘貼在內存中加密和解密***的代碼***使用android密鑰庫的字符串。我無法使用文件訪問權限或共享偏好設置來達到我的應用程序的目的。我重複一遍,必須在記憶中完成。密鑰保存在KeyStore中。 – gmmo

+2

您從'ecryptedText'設置'cipherText'並嘗試base64解碼,但是**並不是base64編碼的**。使用類似'ecryptedText = Base64.encode(/ * BAOS */outputStream.toByteArray,Base64.DEFAULT);' –

回答

1

這裏是你如何使用Android的KeyStore加密/使用ByteArrayOutputStreamByteArrayInputStream解密存儲器串的工作示例。請注意供應商的變更,>= 6使用"AndroidKeyStoreBCWorkaround",舊版本使用"AndroidOpenSSL"。此外,你必須使用Base64.encodeToString這樣編碼加密後的數據爲Base64字符串:

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

我最後的工作示例基於您的代碼

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

產出

D/MainActivity: Encrypt = rejkfeas3HgYnZOlC4S/R3KvlMTyiBjr5T6LqWGj9bq6nvpM0KBsoeYtr4OdCLITFX5GojuO4VpB 
       Hy11n8zc9JcAx4IFW0Aw0/DfCmMDvIomQItBAaIWewZqNHc0UwS0y/JRhAe8SiTz5sFJ6Abvgax6 
       vEfbYT0gzok+qtlfBNQLPvXejquhc0pZBaX1RgKDZyEJh3DBVRaFDgogK8XphaI/xtd1Cww9uO63 
       QxA7HfrFUN8rJXrHF4EMi/yrDxs2xVHGF0v21xeuXRwLW9JXYn4fFAJJ0Jr8N5f03UDuKeNlI568 
       RFVOGH7WpOLvKN4CDlsC+DT4Z8YVIOdtS/tO+Q== 
D/MainActivity: Decrypt = This is a text 

Android Studio Output

UPDATE

對於的Android API 19,你只需要使用以前密鑰庫 API KeyPairGeneratorSpec,而不是KeyGenParameterSpec這樣的:我的聲譽待價而沽

try { 
    Calendar start = Calendar.getInstance(); 
    Calendar end = Calendar.getInstance(); 
    end.add(Calendar.YEAR, 1); 

    KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(this) 
     .setAlias("key1") 
     .setSubject(new X500Principal("CN=Sample Name, O=Android Authority")) 
     .setSerialNumber(BigInteger.ONE) 
     .setStartDate(start.getTime()) 
     .setEndDate(end.getTime()) 
     .build(); 

    KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore"); 
    generator.initialize(spec); 

    // 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"; 

    KeyPair keyPair = generator.generateKeyPair(); 

    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)); 
} 
+0

Christos,感謝您的代碼。我忘記提到的一件事是它需要在API 19上工作。上面的代碼只適用於API 23及更高版本。我需要支持舊設備。你會碰巧知道如何使它在API級別19上工作嗎? – gmmo

+1

@gmmo這很簡單,你只需要使用舊的KeyStore Spec API。請看看我更新的答案。 –

+0

謝謝你克里斯托斯,你救了我鞭子! – gmmo