[英]Is this Java encryption code thread safe?
我想将以下代码用于高并发性应用程序,其中某些数据必须加密和解密。 所以我需要知道应该同步这段代码的哪一部分,如果有的话,以避免不可预测的问题。
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说:
“返回一个新的SecretKeyFactory对象,该对象封装了第一个支持指定算法的Provider的SecretKeyFactorySpi实现。”
此外, 源代码明确地确认创建并返回了新对象。
简而言之,这意味着您的DesEncryptor
类当前不是线程安全的,但您应该能够通过同步相关操作(例如encode
和decode
)使其成为线程安全的,而不是暴露两个Cipher对象。 如果使方法同步可能会产生瓶颈,那么为每个线程创建一个单独的DesEncryptor
实例。
如果它们被多个线程同时使用,那么事情只需要是线程安全的。 因为这个类的每个实例都可能只被一个线程使用,所以不必担心它是否是线程安全的。
在一个不相关的说明,有一个硬编码盐,nonce或IV 从来都不是一个好主意。
Cipher
对象不是线程安全的,因为它保留了有关加密过程的内部状态。 这也适用于您的DesEncrypter
类 - 每个线程都需要使用自己的DesEncrypter
实例,除非您同步encode
和decode
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.