java 客户端和服务端加密_客户端的Java加密和服务器的解密,使用PBKDF2WithHmacSHA1和AES/CBC/PKCS5Padding...

只要私钥保密,并且在解密时我的应用中出现以下错误:javax.crypto.BadPaddingException:给定的最终块未正确填充

代码:

// Encryption, client side

byte[] plainData = "hello plaintext!".getBytes("UTF-8");

byte[] salt = new byte[64];

new SecureRandom().nextBytes(salt);

KeySpec spec = new javax.crypto.spec.PBEKeySpec("password".toCharArray(), salt, 1024, 256);

SecretKey sk = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1").generateSecret(spec);

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(sk.getEncoded(), "AES"));

byte[] iv = cipher.getParameters().getParameterSpec(IvParameterSpec.class).getIV();

byte[] ciphertext = cipher.doFinal(plainData);

System.out.println("ciphertext: "+new String(ciphertext, "UTF-8")); // cipher

// Decryption, server side

KeySpec spec2 = new javax.crypto.spec.PBEKeySpec("password".toCharArray(), salt, 1024, 256);

SecretKey sk2 = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1").generateSecret(spec2);

Cipher cipher2 = Cipher.getInstance("AES/CBC/PKCS5Padding");

cipher2.init(Cipher.DECRYPT_MODE, new SecretKeySpec(sk2.getEncoded(), "AES"), new IvParameterSpec(iv)); // Get the same IV value from client/encryptor aswell, still random

String plaintext = new String(cipher2.doFinal(ciphertext), "UTF-8");

System.out.println("decrypted plaintext: "+plaintext); // plain导致问题的是盐的随机性吗?

当我在客户端使用对象引用时,我可以很好地将其解密,但我需要在服务器上使用自己的实例。

非常感谢您提前纠正我的错误!

*编辑:*代码更新和更正

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值