繁体   English   中英

Java中具有AES256加密的Pr0blem

[英]Pr0blem with AES256 encryption in java

所以..这是课程:(我使用AES256加密技术并为之制造)

public class AES256
{
private String charSet = "UTF-8";
private String algo = "AES/CBC/PKCS5Padding";
private String baseAlgo = "AES";
private String hashAlgo = "PBKDF2WithHmacSHA1";

private String key = null;
private String salt = "defaultsaltsalt";
private String iv = "a1bC@6jZ!#sL1z0y";

private Cipher cipher;
private BufferedInputStream bIs;
private BufferedOutputStream bOs;

public AES256()
{

}

public AES256(String pass)
{
    this.key = pass;
}

public AES256(String pass, String salty)
{
    this.key = pass;
    this.salt = salty;
}

public AES256(String pass, String salty, String ivs)
{
    this.key = pass;
    this.salt = salty;
    this.iv = ivs;
}

public void setKey(String key)
{
    this.key = key;
}

public void setSalt(String salt)
{
    this.salt = salt;
}

public void setIV(String ivs)
{
    this.iv = ivs;
}

/**
 * @Method Pads and constructs the SecretKey (Padding @ 32)
 * @return Returns the padded key.
 * @throws Exception Exception is thrown if the key is null or something else wrong..
 */
public SecretKeySpec getKey() throws Exception
{
     byte[] saltBytes = salt.getBytes(charSet);

     SecretKeyFactory factory = SecretKeyFactory.getInstance(hashAlgo);
     PBEKeySpec spec = new PBEKeySpec(
             this.key.toCharArray(), 
             saltBytes, 
             300000, //make variable
             263 //default 32 bytes
     );

     SecretKey secretKey = factory.generateSecret(spec);
     SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), baseAlgo);

     return secret;
}

/**
 * @Method Pads and returns the IV (Padding @ 16)
 * @return
 * @throws Exception
 */
public byte[] getIV() throws Exception
{
    byte[] byteKey = iv.getBytes(charSet);
    MessageDigest sha = MessageDigest.getInstance("SHA-512");
    byteKey = sha.digest(byteKey);
    byteKey = Arrays.copyOf(byteKey, 16);
    return byteKey;
}

public byte[] encrypt(byte[] plainText) throws Exception
{
    cipher = Cipher.getInstance(algo);
    cipher.init(Cipher.ENCRYPT_MODE, getKey(), new IvParameterSpec(getIV()));

    System.out.println("Plain text length: "+plainText.length);
    byte[] enc = Base64.encodeBase64(cipher.doFinal(plainText));
    System.out.println("Encrypted text length "+enc.length);

    return  enc;
}

public byte[] decrypt(byte[] encryptedText) throws Exception
{
    cipher = Cipher.getInstance(algo);
    cipher.init(Cipher.DECRYPT_MODE, getKey(), new IvParameterSpec(getIV()));

    System.out.println("Encrypted Decrypted Text length: "+encryptedText.length);
    byte[] de = cipher.doFinal(Base64.decodeBase64(encryptedText));
    System.out.println("Decrypted Text length: "+de.length);

    return de;
}

public void encrypt(File fileToEncrypt) throws FileNotFoundException, IOException, Exception
{
    if(fileToEncrypt == null)
        throw new FileNotFoundException("File given to encrypt was not found!");
    File encrypted = new File(cutPath(fileToEncrypt.getPath()), "ENCRYPTED "+fileToEncrypt.getName());
    if(!encrypted.exists())
        encrypted.createNewFile();
    bIs = new BufferedInputStream(new FileInputStream(fileToEncrypt));
    bOs = new BufferedOutputStream(new FileOutputStream(encrypted));

    @SuppressWarnings("unused")
    int read = 0;
    byte[] buff = new byte[1024];
    while((read = bIs.read(buff)) != -1)
    {
        byte[] enc = encrypt(buff);
        bOs.write(enc, 0, enc.length);
    }
    bIs.close();
    bOs.close();
}

public void decrypt(File fileToDecrypt) throws FileNotFoundException, IOException, Exception
{
    if(fileToDecrypt == null)
        throw new FileNotFoundException("File given to decrypt was not found!");
    File decrypted = new File(cutPath(fileToDecrypt.getPath()), "DECRYPTED "+fileToDecrypt.getName().replace("ENCRYPTED ", ""));
    if(!decrypted.exists())
        decrypted.createNewFile();
    bIs = new BufferedInputStream(new FileInputStream(fileToDecrypt));
    bOs = new BufferedOutputStream(new FileOutputStream(decrypted));

    @SuppressWarnings("unused")
    int read = 0;
    byte[] buff = new byte[1388];
    while((read = bIs.read(buff)) != -1)
    {
        byte[] de = decrypt(buff);
        bOs.write(de, 0, de.length);
    }
    bIs.close();
    bOs.close();
}

private String cutPath(String path)
{
    String temp = "";
    String[] parts = path.split(Pattern.quote(File.separator));
    for(int i = 0; i < parts.length-1; i++)
        temp+=parts[i]+"/";
    return temp;
}

}

我正在使用我编写的此类使用CBC / PKCS5PADDING在Java中加密和解密信息,并且我还使用了哈希算法来哈希我的密码。

注意:我知道此程序中存在一些效率问题,例如为什么我要不断计算从文件中获取的密钥。.我稍后将对其进行修复..它只是在那里进行一些测试。

无论如何,我正在使用crypto(File)方法,当我给它一个文件时,它一次获取1024字节的信息,然后对该信息进行加密,然后将其秘密存储到BASE64中,以避免编码问题。然后将其写回到另一个文件中,名称相同,但在其前面...和父文件位于同一目录中的单词ENCRYPTED或DECRYPTED。

现在我的问题是,当它正在加密信息时,我正在向它发送1024字节的信息以进行处理,然后使用BASE64以避免编码问题(例如UTF等)。但是最后,我正在加密的1024字节是如何加密的。变成1388字节的数据,这就是我得到的...现在为什么呢?

第二个问题:除了上述问题之外,它多少有些有用,也许这不是问题,但我很想学习为什么。.无论如何,第二个问题也是使用crypto(File)方法以及解密(File)。文件以某种方式增加了它的额外长度(可能与上面的问题直接相关...),因此,当我解密文件时,文件的文本已被完全解密,但是无论如何我都会在底部得到一些额外的重复文本原因...像文件一样,直到有一些重复的信息为止..所以我不知道这些随机字节来自哪里,但我很想知道。

无论如何,如果您发现我的加密方法有任何其他问题,请在这里告诉我,可能是较弱的加密选择? 也许很容易被强行使用? 使用效率低下的方法? 不明白我要完成的事情吗? 可能喜欢用相同的名称和相同的目录保存文件。是否有更简单的方法?

使用Base-64编码字符串会导致字符串比开始时更长。

这样想吧。 您有一个数组,每个字节有8个有效位。 您最终得到的字符串只有6个重要的位(因此名称中的64位为base-64,因为2 ^ 6 = 64),因此它必须更长大约1/3。

向后工作,使用您拥有的模式的AES加密将添加16个字节的填充,因此结果将比您提供的填充长16个字节。 这意味着您给它1024,然后加密(在base-64编码之前)将导致1040字节的长度。

该算法以这种方式工作:

1024 bytes + 16 padding = 1040 bytes
1040 bytes is not divisible by 3 (as required by base-64) so add 1 byte
1041 bytes * 8 = 8328 bits / 6 = 1388
1388 base-64 characters

第2部分

您的末尾有多余字节的原因是此代码:

byte[] buff = new byte[1024];
while((read = bIs.read(buff)) != -1)
{
    byte[] enc = encrypt(buff);
    bOs.write(enc, 0, enc.length);
}

在最后一次读取时,它不会将完整的1024个字节读入缓冲区。 先前读取的字节仍然存在。

变量“ read”保存实际读取的字节数。 注意如何不使用该变量。 但是您要加密整个缓冲区,而不仅仅是第一个“读取”字节。

您可以通过将'read'的值传递到'encrypt'方法中并使用doFinal(buff, 0, read)方法的另一种形式来对读取的内容进行加密来解决此问题。

更改此行:

    byte[] enc = encrypt(buff, read);

还有这个:

public byte[] encrypt(byte[] plainText, int len) throws Exception

还有这个:

byte[] enc = Base64.encodeBase64(cipher.doFinal(plainText, 0, len));

您将需要执行与解密类似的操作,因为上次读取可能没有1388个字节,并且旧字节将位于缓冲区中。 (您现在没有这个问题了,因为您总是加密1024个字节。只是如果文件在最后一个块上有简短的读取,则其中的一些错误。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM