AES算法安全吗?

时间:2017-10-24 16:11:01

标签: java android algorithm encryption aes

下面是我在为我的android项目研究AES之后整理的算法,我想知道的是,它是否安全并且可以改进吗?我问的原因是因为我看到了很多不同的方法,只需要一些帮助。

先谢谢,我真的很感激任何帮助。

private static final int pswdIterations = 1000;
private static final int keySize = 256;
private static final int saltlength = keySize / 8;

private static final String ENCODING = "UTF-8";
private static final String PBK = "PBKDF2WithHmacSHA1";
private static final String AES = "AES";
private static final String CIPHER = "AES/CBC/PKCS5Padding";

public String encrypt(String plainText) throws Exception {
    //get text from password field
    final String pass = password.getText().toString();
    //get salt from generateSalt() method (see below)
    String salt = generateSalt();
    //convert salt to bytes
    byte[] saltBytes = salt.getBytes(ENCODING);

    // Derive the key from
    SecretKeyFactory factory = SecretKeyFactory.getInstance(PBK);
    PBEKeySpec spec = new PBEKeySpec(
            pass.toCharArray(),
            saltBytes,
            pswdIterations,
            keySize
    );

    //encode key
    SecretKey secretKey = factory.generateSecret(spec);
    SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), AES);

    //encrypt the message
    Cipher cipher = Cipher.getInstance(CIPHER);
    cipher.init(Cipher.ENCRYPT_MODE, secret);
    AlgorithmParameters params = cipher.getParameters();
    byte[] ivBytes = params.getParameterSpec(IvParameterSpec.class).getIV();
    byte[] encryptedTextBytes = cipher.doFinal(plainText.getBytes(ENCODING));

    //encode text and output final encrypted text
    String encodedText = Base64.encodeToString(encryptedTextBytes, Base64.DEFAULT);
    String encodedIV = Base64.encodeToString(ivBytes, Base64.DEFAULT);
    String encodedSalt = Base64.encodeToString(saltBytes, Base64.DEFAULT);
    return encodedSalt +  encodedText + encodedIV;
}

public static String generateSalt() {
    SecureRandom random = new SecureRandom();
    byte bytes[] = new byte[saltlength];
    random.nextBytes(bytes);
    return new String(bytes);
}

1 个答案:

答案 0 :(得分:1)

本质上该方案看起来很安全,但不包括身份验证。

<强>改进:

  1. 在合并结果中包含迭代计数。
  2. 包含版本指示符,可以像单个字节一样简单。
  3. 通常连接字节数组,然后使用一个整体Base64编码。
  4. 备注:
    考虑使用RNCryptor

    请查看RNCryptor-Spec,了解将各种物品打包在一起的示例。