首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Java中使用AES算法

在Java中使用AES算法
EN

Code Review用户
提问于 2019-05-01 16:41:10
回答 1查看 106关注 0票数 0

为了加密GUI中的文件,我使用了AES算法。我在想我的算法是否安全。我能改变什么来改进它吗?我的静脉输液安全吗?每次都会产生不同的随机数吗?我把盐转移成功了吗?

我知道我可以通过为不同的方法创建单独的类来改进这一点,但是我现在只是在主要的方法中这样做。我对密码学很陌生,所以任何反馈都会非常感谢!//作者@Alex公共类AESFileEncryption {

代码语言:javascript
复制
// password to encrypt the file - how long should password be?
private static final String password = "UxIpOqSdNmSTuxZaShPu";

public static void main(String args[]) throws Exception {

    // file to be encrypted
    FileInputStream inF = new FileInputStream(GUI.AESinFile); // 'AESinFile' is a JFileChooser method from my GUI class

    // encrypted file
    FileOutputStream outF = new FileOutputStream("encrypted_file.des");

    // generate and write the salt
    SecureRandom sr = new SecureRandom();
    byte[] salt = new byte[16];
    sr.nextBytes(salt);
    outF.write(salt);

    // generate key
    SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, 65536, 256); // salt, iteration count, key strength
    SecretKey tmp = skf.generateSecret(keySpec);
    SecretKey secretKey = new SecretKeySpec(tmp.getEncoded(), "AES"); // returns key

    // initialise the cipher with secure padding
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, secretKey);
    AlgorithmParameters p = cipher.getParameters();

    // iv used when initializing the cipher to make text more random

    byte[] iv = p.getParameterSpec(IvParameterSpec.class).getIV();
    outF.write(iv);

    // file encryption
    byte[] input = new byte[64];
    int bytesRead;

    while ((bytesRead = inF.read(input)) != -1) {
        byte[] output = cipher.update(input, 0, bytesRead);
        if (output != null)
            outF.write(output);
    }

    byte[] output = cipher.doFinal();
    if (output != null)
        outF.write(output);
        System.out.println("file encrypted");


    inF.close();
    outF.flush();
    outF.close();
    // inputScanner.close();

}

}
EN

回答 1

Code Review用户

发布于 2019-05-01 18:37:47

第105行是一个错误。缩进表示只有当输出不是null时才执行。

但实际上与if语句无关。

您应该始终使用大括号,即使执行只有1行长。这适用于所有的陈述:同时,如果,做,等等。

票数 3
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/219511

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档