2015-05-28 27 views
1

BouncyCastle的提供Threefish的實現,這可能需要一個調整的參數:我可以使用標準Java Cipher API使用BouncyCastle的Tweakable Block Ciphers嗎?

ThreeFishEngine engine = new ThreeFishEngine(256); 
engine.init(true, new TweakableBlockCipherParams(...)); 

然而,TweakableBlockCipherParams不與所使用的Java的默認Cipher的情況下,AlgorithmParameter類型兼容。

有沒有辦法通過調整來初始化這個密碼?

Cipher cipher = Cipher.getInstance("Threefish-256/CBC/NoPadding"); 
cipher.init(???); 

回答

1

您只能使用通過Java的加密API充氣城堡的Threefish算法,如果你不想加密過程中使用的調整參數。通過Java的API,你只能引入一個密鑰和一個初始化向量參數,但是這不會被用作一個調整參數(我解釋了爲什麼之後的代碼示例,見下文)。

此外,對於下面的示例工作,您必須使用Java密碼擴展(JCE)無限強度管轄策略文件更新您的JRE/JDK,您可以從here下載這些文件。 Java 7和8有不同的版本。

如果你不想使用調整參數,你可以通過像這樣的標準加密API來使用Threefish算法。

static final BouncyCastleProvider PROVIDER = new BouncyCastleProvider(); 

public static void main(String[] args) throws Exception { 
    KeyGenerator kg = KeyGenerator.getInstance("Threefish-1024", PROVIDER); 
    kg.init(1024); 
    SecretKey key = kg.generateKey(); 

    byte[] plaintext = "Hi! I'm cat!".getBytes(); 
    byte[] ciphertext = encrypt(key, plaintext); 
    System.out.println(new String(decrypt(key, ciphertext))); 
    // prints "Hi! I'm cat!" 
} 

static byte[] encrypt(SecretKey key, byte[] plaintext) throws Exception { 
    return encryptOrDecrypt(true, key, plaintext); 
} 

static byte[] decrypt(SecretKey key, byte[] ciphertext) throws Exception { 
    return encryptOrDecrypt(false, key, ciphertext); 
} 

static byte[] encryptOrDecrypt(boolean encrypt, SecretKey key, byte[] bytes) throws Exception { 
    Cipher cipher = Cipher.getInstance("Threefish-1024/CBC/PKCS5Padding", PROVIDER); 
    // note that we are creating a dummy iv parameter, in this case it 
    // should be 128 bytes long, because if it's not an exception is raised 
    cipher.init(encrypt ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE, key, new IvParameterSpec(new byte[128])); 
    return cipher.doFinal(bytes); 
} 

我已經下載了一個充氣城堡JAR與調試符號from here和調試上面的代碼。 Cipher.init的電話號碼爲Threefish.init,變量params將爲KeyParameter的實例,而在我們的情況下爲TweakableBlockCipherParameters。因此,tweakBytes將爲空,並且不會在加密期間使用。

知道此信息,現在無法使用Java API將調整參數提供給底層的Threefish密碼引擎。

Link to another very similar question

+0

你確定一個調整是同樣的事情作爲IV?我正在瀏覽源代碼,試圖弄清楚它們是否在同一個地方結束了,而且在我看來,它們確實沒有。 – codebreaker

+0

另外,當我運行這個,我得到一個'InvalidKeyException:非法密鑰大小'。 – codebreaker

+0

@codebreaker你對IV的事情是對的。關於這個和'非法密鑰大小'異常請看我更新我的答案。 –

相關問題