我想要使用以下代碼來實現某些數據必須加密和解密的高併發應用程序。所以我需要知道該代碼的哪一部分應該同步,以避免不可預知的問題。這個Java加密代碼線程安全嗎?
public class DesEncrypter {
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
};
int iterationCount = 19;
DesEncrypter(String passPhrase) {
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);
} catch (...)
}
public String encrypt(String str) {
try {
// Encode the string into bytes using utf-8
byte[] utf8 = str.getBytes("UTF8");
// Encrypt
byte[] enc = ecipher.doFinal(utf8);
// Encode bytes to base64 to get a string
return new sun.misc.BASE64Encoder().encode(enc);
} catch (...)
}
public String decrypt(String str) {
try {
// Decode base64 to get bytes
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
// Decrypt
byte[] utf8 = dcipher.doFinal(dec);
// Decode using utf-8
return new String(utf8, "UTF8");
} catch (...)
}
}
如果我創建的加密(新密碼)和解密()方法每次調用,那麼我能避免併發問題,我只是不知道是否有大量的開銷在獲得一個新的每個調用的密碼實例。
public String encrypt(String str) {
try {
// Encode the string into bytes using utf-8
byte[] utf8 = str.getBytes("UTF8");
// Encrypt
//new cipher instance
ecipher = Cipher.getInstance(key.getAlgorithm());
byte[] enc = ecipher.doFinal(utf8);
// Encode bytes to base64 to get a string
return new sun.misc.BASE64Encoder().encode(enc);
} catch (...)
不知道,謝謝。我計劃在嚴格的操作系統權限下將鹽和密碼短語存儲在單獨的文件中,這些權限僅適用於應用程序。 – user646584 2011-03-15 03:28:51
使用恆定的鹽(即使它受到保護)首先會破壞鹽的使用。 – 2011-03-15 03:39:13
你是說鹽應該在運行時隨機獲得?我很困惑,很明顯,一旦數據被加密後,密碼不能改變,那麼需要事先生成並存儲在安全文件中,鹽和密碼短語,密碼短語等? – user646584 2011-03-15 03:53:50