2012-02-27 88 views
2

我正在運行從互聯網上獲得的java字符串加密/解密類!這裏是幾乎沒有修改的類:產生不同輸出的字符串加密/解密類

public class EncrypterDecrypter { Cipher ecipher; 密碼dcipher;

EncrypterDecrypter(SecretKey key) 
{ 
    try { 
     ecipher = Cipher.getInstance("DES"); 
     dcipher = Cipher.getInstance("DES"); 
     ecipher.init(Cipher.ENCRYPT_MODE, key); 
     dcipher.init(Cipher.DECRYPT_MODE, key); 

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

}

公共類EncryptionTester {

public static void main(String[] args) 
{ 
    try 
    { 
     //Generate a temporary key. 
     SecretKey key = KeyGenerator.getInstance("DES").generateKey(); 

     //Create Encrypter/Decrypter class 
     EncrypterDecrypter crypto = new EncrypterDecrypter(key); 

     //More lines of code to use crypto object 
    } 
    catch (Exception e) 
    { 
    } 
} 

}

我的問題是,每次我創建EncrypterDecrypter類的一個新實例,我得到加密的字符串型動物尚字符串加密仍然是一樣的!我的頭腦告訴我,問題是每當創建一個新實例時SecretKey對象不斷變化,我想知道如何使SecretKey對象對於所有Encrypter/Decrypter類的實例都是相同的問題的原因!

+0

要發佈的相關代碼將是初始化「EncrypterDecrypter」對象的行。你在通過什麼「鑰匙」? – dlev 2012-02-27 06:56:02

+0

你是對的我修改了代碼!我正在通過DES密鑰算法! – Xris 2012-02-27 07:11:22

回答

1

如果您使用的javax.crypto包,然後加密和decryp方法看行不行。 嘗試生成密鑰這樣的:

final SecretKeyFactory skf = SecretKeyFactory.getInstance("DES"); 
final SecretKey key = skf.generateSecret(new DESKeySpec(new byte [] {/*The key*/})); 
instance.EncrypterDecrypter(key);      //Initialization of your Cipher objects 
String encrypted = instance.encrypt("This is a test"); 
System.out.println(instance.decrypt(encrypted));  //"This is a test" 

你應該做的事漁獲。

+0

DESKeySpec是哪個軟件包? – Xris 2012-02-27 07:32:38

+0

找到該產品:javax.crypto.spec – Jerome 2012-02-27 07:44:17

+0

什麼是關鍵?鑰匙的尺寸是否有限? Thanx – Xris 2012-02-27 07:49:43

1

從字節數組生成SecretKey的..

byte raw[] = new byte[]{0x001,0x002,0X002,0X002,0X002,0X002,0X002,0X002,0X002,0X002,0X002,0X002,0X002,0X002,0X002,0X002}; 
     SecretKeySpec spec = new SecretKeySpec(raw, "DES");