use*_*584 10 java encryption cryptography thread-safety
我想将以下代码用于高并发性应用程序,其中某些数据必须加密和解密.所以我需要知道应该同步这段代码的哪一部分,如果有的话,以避免不可预测的问题.
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 (...)
}
}
Run Code Online (Sandbox Code Playgroud)
如果我在每个调用的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 (...)
Run Code Online (Sandbox Code Playgroud)
Ste*_*n C 13
标准规则是 - 除非Javadoc明确声明Java库中的类是线程安全的,否则您应该假设它不是.
在这个特定的例子中:
该Cipher.getInstance(...)
和SecretKeyFactory.getInstance(...)
方法被记录为返回新对象; 即不引用其他线程可能引用的现有对象.
更新 - javadoc说:
"返回一个新的SecretKeyFactory对象,该对象封装了第一个支持指定算法的Provider的SecretKeyFactorySpi实现."
此外,源代码明确地确认创建并返回了新对象.
简而言之,这意味着您的DesEncryptor
类当前不是线程安全的,但您应该能够通过同步相关操作(例如encode
和decode
)以及不暴露两个Cipher对象来使其成为线程安全的.如果使方法同步可能会产生瓶颈,那么DesEncryptor
为每个线程创建一个单独的实例.
仅当事物同时被多个线程使用时才需要线程安全。由于此类的每个实例可能仅由一个线程使用,因此无需担心它是否是线程安全的。
顺便说一句,使用硬编码的 salt、nonce 或 IV从来都不是一个好主意。
归档时间: |
|
查看次数: |
13736 次 |
最近记录: |