2017-10-21 183 views
1

我會嘗試使用RC6算法,但我有一個錯誤:RC6密鑰生成器不可用

RC6的KeyGenerator不可

我怎樣才能獲得RC6的的KeyGenerator?

異常線程 「main」 java.security.NoSuchAlgorithmException:RC6的KeyGenerator在javax.crypto.KeyGenerator不可 (KeyGenerator.java:169) 在javax.crypto.KeyGenerator.getInstance(KeyGenerator.java:223 ) 在RC6.encrypt(RC6.java:27) 在RC6.main(RC6.java:16)

import javax.crypto.spec.*; 
import java.security.*; 
import javax.crypto.*; 

public class Main 
{ 
    private static String algorithm = "RC6"; 

    public static void main(String []args) throws Exception { 
     String toEncrypt = "The shorter you live, the longer you're dead!"; 

     System.out.println("Encrypting..."); 
     byte[] encrypted = encrypt(toEncrypt, "password"); 

     System.out.println("Decrypting..."); 
     String decrypted = decrypt(encrypted, "password"); 

     System.out.println("Decrypted text: " + decrypted); 
    } 

    public static byte[] encrypt(String toEncrypt, String key) throws Exception { 
     // create a binary key from the argument key (seed) 
     SecureRandom sr = new SecureRandom(key.getBytes()); 
     KeyGenerator kg = KeyGenerator.getInstance(algorithm); 
     kg.init(sr); 
     SecretKey sk = kg.generateKey(); 

     // create an instance of cipher 
     Cipher cipher = Cipher.getInstance(algorithm); 

     // initialize the cipher with the key 
     cipher.init(Cipher.ENCRYPT_MODE, sk); 

     // enctypt! 
     byte[] encrypted = cipher.doFinal(toEncrypt.getBytes()); 

     return encrypted; 
    } 

    public static String decrypt(byte[] toDecrypt, String key) throws Exception { 
     // create a binary key from the argument key (seed) 
     SecureRandom sr = new SecureRandom(key.getBytes()); 
     KeyGenerator kg = KeyGenerator.getInstance(algorithm); 
     kg.init(sr); 
     SecretKey sk = kg.generateKey(); 

     // do the decryption with that key 
     Cipher cipher = Cipher.getInstance(algorithm); 
     cipher.init(Cipher.DECRYPT_MODE, sk); 
     byte[] decrypted = cipher.doFinal(toDecrypt); 

     return new String(decrypted); 
    } 
} 

回答

2

RC6不是由Oracle安全供應商之一所提供的算法。提供商提供的算法實現落後於Cipher,實際上是KeyGenerator

這應該工作,在classpath中加入充氣城堡供應商的.jar後:

static { 
    Security.addProvider(new BouncyCastleProvider()); 
} 

您可能還需要在你的JRE文件夾中安裝了無限的加密文件。

+0

嗨馬丁,謝謝你的回答。是的,我已經安裝了無限加密技術。我已經下載並從這裏https://www.bouncycastle.org/latest_releases.html把Bouncy Castle的罐子,然後我把行Security.addProvider(新的BouncyCastleProvider())在主。但現在我有這個錯誤(在解密行):**墊塊損壞**爲什麼?有問題? – narraccino

+1

我不知道什麼是錯的。這可能是使用錯誤的密鑰或密文的更改。在我的系統上,您的代碼正常工作。請注意,RC6是一個分組密碼。您需要確保您使用正確的操作模式*和IV,因爲Java和BC提供商傾向於支持ECB模式,這是不安全的。但是,在你開始工作後,這是一件值得擔心的事情。 –

+0

我分心了,對不起,在解密中還有另一個keyGenerator。非常感謝你! – narraccino