我想将以下代码用于需要对某些数据进行加密和解密的高并发应用程序。所以我需要知道应该同步这段代码的哪一部分(如果有的话),以避免出现不可预知的问题。
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 (...)
}
}
如果我在每次调用的 encrypt() 和 decrypt() 方法中创建一个新的密码,那么我可以避免并发问题,我只是不确定获取密码的新实例是否有很多开销对于每次调用。
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 (...)
最佳答案
标准规则是 - 除非 Javadoc 明确声明 Java 库中的类是线程安全的,否则您应该假设它不是。
在这个特定的例子中:
- 各种类都没有记录为线程安全的。
Cipher.getInstance(...)
和SecretKeyFactory.getInstance(...)
方法被记录为返回新对象;即不引用其他线程可能引用的现有对象。更新 - javadoc是这样说的:
"A new SecretKeyFactory object encapsulating the SecretKeyFactorySpi implementation from the first Provider that supports the specified algorithm is returned."
此外,source code清楚地确认创建并返回了一个新对象。
简而言之,这意味着您的 DesEncryptor
类当前不是线程安全的,但您应该能够通过同步相关操作(例如 encode
和 decode
),并且不公开这两个 Cipher 对象。如果使方法同步可能会造成瓶颈,则为每个线程创建一个单独的 DesEncryptor
实例。
关于java - 这个Java加密代码线程安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5307132/