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

  1. public void sendfile() {
  2. fis = new FileInputStream(file);
  3. bis = new BufferedInputStream(fis);
  4. byte[] byteArray = new byte[1024];
  5. int bytesCount = 0;
  6. while ((bytesCount = fis.read(byteArray)) >= 0) {
  7. String encryptString = new String(byteArray, "UTF-8");
  8. bos.write(EncryptAES.encrypt(encryptString, "12345").getBytes("UTF-8"));
  9. }
  10. }
  11. public void receiveFile(File file, BufferedInputStream bis) {
  12. fos = new FileOutputStream(file);
  13. bos = new BufferedOutputStream(fos);
  14. byte[] byteArray = new byte[1024];
  15. int bytesCount = 0;
  16. while ((bytesCount = bis.read(byteArray)) >= 0) {
  17. String encryptString = new String(byteArray, "UTF-8");
  18. bos.write(EncryptAES.decrypt(encryptString, "12345").getBytes("UTF-8"));
  19. }
  20. }
  21. public static String encrypt(String content,SecretKey secretKey) {
  22. byte[] enCodeFormat = secretKey.getEncoded();
  23. SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
  24. Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
  25. cipher.init(Cipher.ENCRYPT_MODE, secretKey);
  26. byte[] byteContent = cipher.doFinal(content.getBytes("UTF-8"));
  27. return Base64.getEncoder().withoutPadding().encodeToString(byteContent);
  28. }
  29. public static String decrypt(String content,SecretKey secretKey) {
  30. byte[] enCodeFormat = secretKey.getEncoded();
  31. SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
  32. Security.addProvider(new BouncyCastleProvider());
  33. Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding", "BC");
  34. cipher.init(Cipher.DECRYPT_MODE, key);
  35. byte[] byteCipherText = Base64.getDecoder().decode(content);
  36. String encryptString = new String(byteCipherText, "UTF-8");
  37. byte[] decryptedText = cipher.doFinal(byteCipherText);
  38. encryptString = new String(decryptedText, "UTF-8");
  39. return new String(decryptedText, "UTF-8");
  40. }