提问者:小点点

Java相当于SecureString


我正在寻找Java的等价物。NET的SecureString. aspx。2018年有这样的实现吗?

OWASP实现并不完全相同,因为它只是一个普通的char数组。虽然。NET等效项提供了额外的功能,例如从/到非托管内存获取实例的能力以及加密。

我知道常见的Java模式,将密码作为char[]传递,并在使用后用零来执行Array. ill()。但是它需要始终围绕char[]构建一个简单的实用程序类。


共3个答案

匿名用户

Oracle有一个GuardedString实现。它最接近NET的SecureString解决方案。

安全字符串实现,解决了与将密码保留为java. lang.String相关的问题。也就是说,任何表示为String的内容都作为明文密码保存在内存中,并且至少在被垃圾回收之前一直保留在内存中。

GuardedString类通过将字符以加密形式存储在内存中来缓解这个问题。加密密钥将是随机生成的密钥。

在其序列化形式中,GuardedString将使用已知的默认密钥进行加密。这是为了提供最低级别的保护,而不管传输如何。对于与远程连接器框架的通信,建议部署启用SSL以实现真正的加密。

应用程序可能还希望持久化GuardedString。在Identity Manager的情况下,它应该将GuardedString转换为EncryptedData,以便可以使用Identity Manager的管理加密功能存储和管理它们。其他应用程序可能希望将APIConfiguration作为一个整体进行序列化。这些应用程序负责加密APIConfigurationblob以获得额外的安全层(超出GuardedString提供的基本默认密钥加密)。

匿名用户

我修改了OWASP版本以随机填充内存中的char数组,因此静态的char数组不会与实际字符一起存储。

import java.security.SecureRandom;
import java.util.Arrays;


/**
* This is not a string but a CharSequence that can be cleared of its memory.
* Important for handling passwords. Represents text that should be kept
* confidential, such as by deleting it from computer memory when no longer
* needed or garbaged collected.
*/
public class SecureString implements CharSequence {

   private final int[] chars;
   private final int[] pad;

   public SecureString(final CharSequence original) {
      this(0, original.length(), original);
   }

   public SecureString(final int start, final int end, final CharSequence original) {
      final int length = end - start;
      pad = new int[length];
      chars = new int[length];
      scramble(start, length, original);
   }

   @Override
   public char charAt(final int i) {
      return (char) (pad[i] ^ chars[i]);
   }

   @Override
   public int length() {
      return chars.length;
   }

   @Override
   public CharSequence subSequence(final int start, final int end) {
      return new SecureString(start, end, this);
   }

   /**
    * Convert array back to String but not using toString(). See toString() docs
    * below.
    */
   public String asString() {
      final char[] value = new char[chars.length];
      for (int i = 0; i < value.length; i++) {
         value[i] = charAt(i);
      }
      return new String(value);
   }

   /**
    * Manually clear the underlying array holding the characters
    */
   public void clear() {
      Arrays.fill(chars, '0');
      Arrays.fill(pad, 0);
   }

   /**
    * Protect against using this class in log statements.
    * <p>
    * {@inheritDoc}
    */
   @Override
   public String toString() {
      return "Secure:XXXXX";
   }

   /**
    * Called by garbage collector.
    * <p>
    * {@inheritDoc}
    */
   @Override
   public void finalize() throws Throwable {
      clear();
      super.finalize();
   }

   /**
    * Randomly pad the characters to not store the real character in memory.
    *
    * @param start start of the {@code CharSequence}
    * @param length length of the {@code CharSequence}
    * @param characters the {@code CharSequence} to scramble
    */
   private void scramble(final int start, final int length, final CharSequence characters) {
      final SecureRandom random = new SecureRandom();
      for (int i = start; i < length; i++) {
         final char charAt = characters.charAt(i);
         pad[i] = random.nextInt();
         chars[i] = pad[i] ^ charAt;
      }
   }

}

匿名用户

这个答案为@sanketshah的伟大回答增加了一点解释。

以下代码显示了用法:

import org.identityconnectors.common.security.GuardedString;

import java.security.SecureRandom;

public class Main {
    public static void main(String[] args) {
        /*
         * Using:
         *   "password".toCharArray();
         * would create an immutable String "password",
         * which remains in memory until GC is called.
         */
        char[] password = new char[]{'p', 'a', 's', 's', 'w', 'o', 'r', 'd'};
        GuardedString guardedString = new GuardedString(password);

        /*
         * Securely wipe the char array by storing random values in it.
         * Some standards require multiple rounds of overwriting; see:
         * https://en.wikipedia.org/wiki/Data_erasure#Standards
         */
        SecureRandom sr = new SecureRandom();
        for (int i = 0; i < password.length; i++)
            password[i] = (char) sr.nextInt(Character.MAX_VALUE + 1);
        //noinspection UnusedAssignment
        password = null;

        /*
         * At some later point in the code, we might need the secret.
         * Here's how to obtain it using Java 8+ lambdas.
         */

        guardedString.access(chars -> {
            for (char c : chars) {
                System.out.print(c);
            }
        });
    }
}

GuardedString可以从maven IdtyConnectors: Framework获得。但是,对于实际实现,还需要IdtyConnectors:Framework内部。

更准确地说,前一个包定义了Encryptor接口:

package org.identityconnectors.common.security;

/**
 * Responsible for encrypting/decrypting bytes. Implementations
 * are intended to be thread-safe.
 */
public interface Encryptor {
    /**
     * Decrypts the given byte array
     * @param bytes The encrypted bytes
     * @return The decrypted bytes
     */
    public byte [] decrypt(byte [] bytes);
    /**
     * Encrypts the given byte array
     * @param bytes The clear bytes
     * @return The ecnrypted bytes
     */
    public byte [] encrypt(byte [] bytes);
}

它由第二个包中的EncryptorImpl实现。(抽象类EncryptorFactory也是如此,它由EncryptorFactoryImpl扩展)。

EncryptorFactory实际上修复了它的实现:

// At some point we might make this pluggable, but for now, hard-code
private static final String IMPL_NAME = "org.identityconnectors.common.security.impl.EncryptorFactoryImpl";

实现的一个不安全的方面是它们使用带有硬编码IV和密钥的AES/CBC/PKCS5PaddEncryptorFactoryImpl的构造函数将true传递给EncryptorImpl

public EncryptorFactoryImpl() {
    _defaultEncryptor = new EncryptorImpl(true);
}

这会导致它使用默认键。尽管如此,IV始终是固定的:

public EncryptorImpl( boolean defaultKey ) {
    if ( defaultKey ) {
        _key = new SecretKeySpec(_defaultKeyBytes,ALGORITHM);
        _iv  = new IvParameterSpec(_defaultIvBytes);            
    }
    else {
        try {
            _key = KeyGenerator.getInstance(ALGORITHM).generateKey();
            _iv  = new IvParameterSpec(_defaultIvBytes);
        }
        catch (RuntimeException e) {
            throw e;
        }
        catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

这里有一些改进的空间:

  1. 使用AES/CTR或AES/GCM代替AES/CBC。(参见分组密码操作模式。)
  2. 始终使用随机IV和密钥。
  3. GuardedString使用内部方法SecurityUtil. lear()来清除字节数组,它将字节归零。有其他可能的数据擦除算法会很好。