搜索
首页Javajava教程为什么 Java AES/CBC 解密后初始字节不正确,如何修复?

Why are the initial bytes incorrect after Java AES/CBC decryption, and how can I fix it?

Java AES/CBC 解密后初始字节不正确

问题:

尝试时在Java中解密AES/CBC加密的字符串,解密结果的初始字节是错误的。

示例:

以下代码演示了该问题:

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AESEncryptionExample {

  public static void encryptDecryptString() {
    try {
      String key = "mySecretKey";
      String value = "This is a test message";
      String initVector = "initializationVector"; // 16-byte (128-bit) initialization vector

      IvParameterSpec iv = new IvParameterSpec(initVector.getBytes());
      SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(), "AES");

      // Create encrypt cipher
      Cipher encryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
      encryptCipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
      byte[] encryptedBytes = encryptCipher.doFinal(value.getBytes());

      // Create decrypt cipher
      Cipher decryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
      decryptCipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
      byte[] decryptedBytes = decryptCipher.doFinal(encryptedBytes);

      System.out.println("Original: " + value);
      System.out.println("Decrypted: " + new String(decryptedBytes));
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public static void main(String[] args) {
    encryptDecryptString();
  }
}

运行此代码时,解密的输出可能会出现类似的情况至:

Result: `£eB6O�geS��i are you? Have a nice day.

解决方案:

由于在处理加密/解密数据时缺少 Base64 编码/解码,导致解密字符串中的初始字节不正确。要解决此问题,应在传输加密字节之前对加密字节进行 Base64 编码,并在解密之前对接收到的加密字节进行 Base64 解码。

更新示例:

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import java.util.Base64;

public class CipherAESBase64 {

  public static void encryptDecryptString() {
    try {
      String key = "mySecretKey";
      String value = "This is a test message";
      String initVector = "initializationVector"; // 16-byte (128-bit) initialization vector

      IvParameterSpec iv = new IvParameterSpec(initVector.getBytes());
      SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(), "AES");

      // Create encrypt cipher
      Cipher encryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
      encryptCipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
      byte[] encryptedBytes = encryptCipher.doFinal(value.getBytes());

      // Encode the encrypted bytes into a Base64 string
      String encryptedString = Base64.getEncoder().encodeToString(encryptedBytes);

      // Create decrypt cipher
      Cipher decryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
      decryptCipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);

      // Decode the encrypted Base64 string into bytes
      byte[] decryptedBytes = Base64.getDecoder().decode(encryptedString);

      // Decrypt the decoded bytes
      byte[] decryptedBytes = decryptCipher.doFinal(decryptedBytes);

      System.out.println("Original: " + value);
      System.out.println("Decrypted: " + new String(decryptedBytes));
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public static void main(String[] args) {
    encryptDecryptString();
  }
}

以上是为什么 Java AES/CBC 解密后初始字节不正确,如何修复?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
Java平台独立性:与不同的操作系统的兼容性Java平台独立性:与不同的操作系统的兼容性May 13, 2025 am 12:11 AM

JavaachievesPlatFormIndependencethroughTheJavavIrtualMachine(JVM),允许Codetorunondifferentoperatingsystemsswithoutmodification.thejvmcompilesjavacodeintoplatform-interploplatform-interpectentbybyteentbytybyteentbybytecode,whatittheninternterninterpretsandectectececutesoneonthepecificos,atrafficteyos,Afferctinginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginging

什么功能使Java仍然强大什么功能使Java仍然强大May 13, 2025 am 12:05 AM

JavaispoperfulduetoitsplatFormitiondence,对象与偏见,RichstandardLibrary,PerformanceCapabilities和StrongsecurityFeatures.1)Platform-dimplighandependectionceallowsenceallowsenceallowsenceallowsencationSapplicationStornanyDevicesupportingJava.2)

顶级Java功能:开发人员的综合指南顶级Java功能:开发人员的综合指南May 13, 2025 am 12:04 AM

Java的顶级功能包括:1)面向对象编程,支持多态性,提升代码的灵活性和可维护性;2)异常处理机制,通过try-catch-finally块提高代码的鲁棒性;3)垃圾回收,简化内存管理;4)泛型,增强类型安全性;5)ambda表达式和函数式编程,使代码更简洁和表达性强;6)丰富的标准库,提供优化过的数据结构和算法。

Java真的平台独立吗? '写一次,在任何地方运行”如何起作用Java真的平台独立吗? '写一次,在任何地方运行”如何起作用May 13, 2025 am 12:03 AM

javaisnotirelyPlatemententduetojvmvariationsandnativecodinteintration,butitlargelyupholdsitsitsworapromise.1)javacompilestobytecoderunbythejvm

揭示JVM:您了解Java执行的关键揭示JVM:您了解Java执行的关键May 13, 2025 am 12:02 AM

thejavavirtualmachine(JVM)IsanabtractComputingmachinecrucialforjavaexecutionasitrunsjavabytecode,使“ writeononce,runanywhere”能力

Java仍然是基于新功能的好语言吗?Java仍然是基于新功能的好语言吗?May 12, 2025 am 12:12 AM

Javaremainsagoodlanguageduetoitscontinuousevolutionandrobustecosystem.1)Lambdaexpressionsenhancecodereadabilityandenablefunctionalprogramming.2)Streamsallowforefficientdataprocessing,particularlywithlargedatasets.3)ThemodularsystemintroducedinJava9im

是什么使Java很棒?关键特征和好处是什么使Java很棒?关键特征和好处May 12, 2025 am 12:11 AM

Javaisgreatduetoitsplatformindependence,robustOOPsupport,extensivelibraries,andstrongcommunity.1)PlatformindependenceviaJVMallowscodetorunonvariousplatforms.2)OOPfeatureslikeencapsulation,inheritance,andpolymorphismenablemodularandscalablecode.3)Rich

前5个Java功能:示例和解释前5个Java功能:示例和解释May 12, 2025 am 12:09 AM

Java的五大特色是多态性、Lambda表达式、StreamsAPI、泛型和异常处理。1.多态性让不同类的对象可以作为共同基类的对象使用。2.Lambda表达式使代码更简洁,特别适合处理集合和流。3.StreamsAPI高效处理大数据集,支持声明式操作。4.泛型提供类型安全和重用性,编译时捕获类型错误。5.异常处理帮助优雅处理错误,编写可靠软件。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用