java 这个Java加密代码线程安全吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5307132/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is this Java encryption code thread safe?
提问by user646584
I want to use the following code for a high-concurrency application where certain data must be encrypted and decrypted. So I need to know what part of this code should be synchronized, if any, to avoid unpredictable issues.
我想将以下代码用于必须加密和解密某些数据的高并发应用程序。所以我需要知道这段代码的哪一部分应该同步,如果有的话,以避免出现不可预测的问题。
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 (...)
}
}
If I create a new cipher in the encrypt() and decrypt() methods for each invocation, then I can avoid concurrency problems, I'm just not sure if there's a lot of overhead in getting a new instance of a cipher for each invocation.
如果我在 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 (...)
采纳答案by Nick Johnson
Things only need to be thread-safe if they're used by multiple threads at once. Since each instance of this class will presumably be used by only a single thread, there's no need to worry about whether it's threadsafe or not.
如果它们一次被多个线程使用,那么它们只需要是线程安全的。由于这个类的每个实例大概只会被一个线程使用,所以不必担心它是否是线程安全的。
On an unrelated note, having a hardcoded salt, nonce or IV is nevera good idea.
顺便提一下,使用硬编码的 salt、nonce 或 IV从来都不是一个好主意。
回答by Stephen C
The standard rule is - unless the Javadoc states explicitly that a class in the Java libraries is thread-safe, you should assumethat it is not.
标准规则是 - 除非 Javadoc 明确声明 Java 库中的类是线程安全的,否则您应该假设它不是。
In this particular instance:
在这个特定的例子中:
- The various classes are not documented as thread-safe.
The
Cipher.getInstance(...)
andSecretKeyFactory.getInstance(...)
methods ARE documented as returning new objects; i.e. not references to existing objects that other threads might have references to.UPDATE- The javadocsays this:
"A new SecretKeyFactory object encapsulating the SecretKeyFactorySpi implementation from the first Provider that supports the specified algorithm is returned."
Furthermore, the source codeplainly confirms that a new object is created and returned.
- 各种类没有被记录为线程安全的。
该
Cipher.getInstance(...)
和SecretKeyFactory.getInstance(...)
方法被记录为返回新对象; 即不引用其他线程可能引用的现有对象。更新- javadoc说:
“返回一个新的 SecretKeyFactory 对象,该对象封装了来自支持指定算法的第一个 Provider 的 SecretKeyFactorySpi 实现。”
此外,源代码清楚地确认创建并返回了一个新对象。
In short, this means that your DesEncryptor
class is not currently thread-safe, but you should be able to make it thread-safe by synchronizing the relevant operations (e.g. encode
and decode
), and not exposing the two Cipher objects. If making the methods synchronized is likely to create a bottleneck, then create a separate instance of DesEncryptor
for each thread.
简而言之,这意味着您的DesEncryptor
类当前不是线程安全的,但是您应该能够通过同步相关操作(例如encode
和decode
)来使其成为线程安全的,并且不公开两个 Cipher 对象。如果使方法同步可能会造成瓶颈,DesEncryptor
则为每个线程创建一个单独的实例。
回答by David Gelhar
The Cipher
object is not going to be thread-safe, because it retains internal state about the encryption process. That applies to your DesEncrypter
class as well - each thread will need to use its own instance of DesEncrypter
, unless you synchonize the encode
and decode
methods.
该Cipher
对象不会是线程安全的,因为它保留有关加密过程的内部状态。这也适用于您的DesEncrypter
类 - 每个线程都需要使用自己的 实例DesEncrypter
,除非您同步encode
和decode
方法。