2012-10-12 32 views
3

每次我使用相同的密碼運行安裝方法時,我每次都會得到不同的密鑰結果。我正在使用關鍵結果來檢查解密密碼是否正確,以防止不必要的解密。使用相同的密碼在Android中獲取不同的加密密鑰結果

我在java中運行下面的代碼,我沒有問題,但在Android中它產生了不同的鍵的問題。有人能告訴我什麼是問題以及如何解決這個問題。我想在Android和Java之間有共同的軟件。

,當我在Android上運行的程序中,我拿到鑰匙[email protected]

當我在Java中運行該程序,我得到關鍵 com.sun.crypto.Provider.PBEKey @ 12345678

private static byte[] bytes; 
    Cipher ecipher; 
    Cipher dcipher; 

    // 8-byte Salt 
    byte[] salt = { 
     (byte)0xA9, (byte)0x9B, (byte)0xC8, (byte)0x32, 
     (byte)0x56, (byte)0x35, (byte)0xE3, (byte)0x03 
    }; 

    // Iteration count 
    int iterationCount = 19; 

    public String setup(String passPhrase) 
    { 
     String output = null; 
     try { 
      // Create the key 
      KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount); 
      SecretKey key = SecretKeyFactory.getInstance(
       "PBEWithMD5AndDES").generateSecret(keySpec); 

      ecipher = Cipher.getInstance(key.getAlgorithm()); 
      dcipher = Cipher.getInstance(key.getAlgorithm()); 

      // Prepare the parameter to the ciphers 
      AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount); 

      // Create the ciphers 
      ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec); 
      dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec); 

      // print key 
      System.out.println("key = " + key); 
      System.out.println("paramSpec = " + paramSpec); 


      output = key.toString(); 
     // showToast("setting up key " + output); 
     // showToast("key size " + output.length()); 
      System.out.println("key Size " + output.length()); 

     } catch (java.security.InvalidAlgorithmParameterException e) { 
     } catch (java.security.spec.InvalidKeySpecException e) { 
     } catch (javax.crypto.NoSuchPaddingException e) { 
     } catch (java.security.NoSuchAlgorithmException e) { 
     } catch (java.security.InvalidKeyException e) { 
     } 

     return output; 
    } 

回答

1

更改行:

SecretKey key = SecretKeyFactory.getInstance(
       "PBEWithMD5AndDES").generateSecret(keySpec); 

SecretKey key = SecretKeyFactory.getInstance(
       "PBEWithMD5AndDES","BC").generateSecret(keySpec); 

像這樣,你特別要求一個加密提供者(充氣城堡) 注意:你將不得不添加bouncycastle提供者到你的虛擬機。

1

也許我誤解了這個問題,但它聽起來像你想要的密鑰的實際內容 - 密鑰的真實價值,作爲一個字節序列,這將執行加密。

文本[email protected]不是密鑰的真實值。這只是意味着JCEPBEKEY類不會覆蓋默認的toString實現。拿到鑰匙的字節數組的實際值,使用

byte [] keyBytes = key.getEncoded(); 

[更新/回縮]

在JVM我會使用以下方法來打印這是一個十六進制字符串:

String keyString = javax.xml.bind.DatatypeConverter.printHexBinary(keyBytes); 

但如前所述,這不適用於Android。 @ user1024882的答案看起來像是一種很好的方法,可以在任一平臺上運行。

+1

記住'java.xml.bind'等不適用於Android,但也有其他的方法來轉換爲十六進制( 'BigInteger','String.format()'等)。 –

+0

非常感謝。我已經更新了答案。 –

1

而不是使用javax.xml lib中您可以使用

static String byteToHex(byte[] keyBytes) 
{ 
    StringBuilder sb = new StringBuilder(); 
    for (byte b : keyBytes) { 
     sb.append(String.format("%1$02X", b)); 
    } 

    return sb.toString(); 
} 
相關問題