aes+base64解密文件出现乱码

p1iqtdky  于 2021-06-29  发布在  Java
关注(0)|答案(0)|浏览(643)

我用socket来传输文件,aes 256来加密/解密,我用字节数组来接受文件的内容并加密,但只有第一个字节大小的数组解密成功,其他出现了乱码(加密的字节大小扩展到1368,aes块大小是128位,不确定是否有效果),下面是我的代码:

public void sendfile() {
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            byte[] byteArray = new byte[1024];
            int bytesCount = 0;
            while ((bytesCount = fis.read(byteArray)) >= 0) {
                String encryptString = new String(byteArray, "UTF-8");
                bos.write(EncryptAES.encrypt(encryptString, "12345").getBytes("UTF-8"));                    
            }
      }
   public void receiveFile(File file, BufferedInputStream bis) {
        fos = new FileOutputStream(file);
        bos = new BufferedOutputStream(fos);
        byte[] byteArray = new byte[1024];
        int bytesCount = 0;
        while ((bytesCount = bis.read(byteArray)) >= 0) {
                String encryptString = new String(byteArray, "UTF-8");
                bos.write(EncryptAES.decrypt(encryptString, "12345").getBytes("UTF-8"));
        }
}

public static String encrypt(String content,SecretKey secretKey) {       
        byte[] enCodeFormat = secretKey.getEncoded();
        SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] byteContent = cipher.doFinal(content.getBytes("UTF-8"));
        return Base64.getEncoder().withoutPadding().encodeToString(byteContent);
}
 public static String decrypt(String content,SecretKey secretKey) {
        byte[] enCodeFormat = secretKey.getEncoded();
        SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
        Security.addProvider(new BouncyCastleProvider());
        Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding", "BC");
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] byteCipherText = Base64.getDecoder().decode(content);
        String encryptString = new String(byteCipherText, "UTF-8");
        byte[] decryptedText = cipher.doFinal(byteCipherText);
        encryptString = new String(decryptedText, "UTF-8");
        return new String(decryptedText, "UTF-8");      
}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题