这个Java加密代码线程安全吗?

时间:2011-03-15 03:13:01

标签: 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 (...)
    }
}

如果我在每次调用的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 (...)

3 个答案:

答案 0 :(得分:12)

标准规则是 - 除非Javadoc明确声明Java库中的类是线程安全的,否则你应该假设它不是。

在这个特定的例子中:

  • 各种类未记录为线程安全的。
  • Cipher.getInstance(...)SecretKeyFactory.getInstance(...)方法记录为返回新对象;即不引用其他线程可能引用的现有对象。

    更新 - javadoc说明了这一点:

      

    “返回一个新的SecretKeyFactory对象,该对象封装了第一个支持指定算法的Provider的SecretKeyFactorySpi实现。”

    此外,source code明确确认创建并返回了新对象。

简而言之,这意味着您的DesEncryptor类当前不是线程安全的,但您应该能够通过同步相关操作使其成为线程安全的(例如encode和{{1并且不暴露两个Cipher对象。如果使方法同步可能会产生瓶颈,那么为每个线程创建一个单独的decode实例。

答案 1 :(得分:3)

如果多个线程同时使用它们,那么它们只需要是线程安全的。因为这个类的每个实例都可能只被一个线程使用,所以不必担心它是否是线程安全的。

在一个不相关的说明中,使用硬编码的盐,nonce或IV 永远不会一个好主意。

答案 2 :(得分:1)

Cipher对象不是线程安全的,因为它保留了有关加密过程的内部状态。这同样适用于您的DesEncrypter类 - 每个线程都需要使用自己的DesEncrypter实例,除非您同步encodedecode方法。

相关问题