java客户端与服务器信息加密,Java AES加密 - 在客户端和服务器之间发送初始化向量...

我在客户端生成初始化向量,其中消息被加密,然后与解密向量一起发送到服务器。Java AES加密 - 在客户端和服务器之间发送初始化向量

客户端代码:

String key1 = "1234567812345678";

byte[] key2 = key1.getBytes();

SecretKeySpec secret = new SecretKeySpec(key2, "AES");

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

cipher.init(Cipher.ENCRYPT_MODE, secret);

byte[] encrypted = cipher.doFinal(msg.getBytes(StandardCharsets.UTF_8));

byte[] iv = cipher.getIV();

String text = DatatypeConverter.printBase64Binary(encrypted);

System.out.println("Encrypted info: " + text);

bytebuf = ByteBuffer.allocate(1024);

bytebuf.clear();

// send iv

bytebuf.put(iv);

bytebuf.flip();

while(bytebuf.hasRemaining()) {

nBytes += client.write(bytebuf);

System.out.println("Iv sent!");

}

bytebuf.clear();

bytebuf.put(text.getBytes());

bytebuf.flip();

while(bytebuf.hasRemaining()) {

nBytes += client.write(bytebuf);

}

服务器代码

LOGGER.info("Confirming write");

byte[] iv = buf.array();

LOGGER.info("Data packet found as {}", iv);

LOGGER.info("Confirming write");

String data = new String(buf.array());

LOGGER.info("Data packet found as {}", data);

IvParameterSpec ivspec = new IvParameterSpec(iv);

String key1 = "1234567812345678";

byte[] key2 = key1.getBytes();

SecretKeySpec secret = new SecretKeySpec(key2, "AES");

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

cipher.init(Cipher.DECRYPT_MODE, secret, ivspec);

byte[] encrypted = DatatypeConverter.parseBase64Binary(data);

byte[] decrypted = cipher.doFinal(encrypted);

System.out.println("Decrypted Info: " + new String(decrypted, StandardCharsets.UTF_8));

我得到以下异常:

java.security.InvalidAlgorithmParameterException: Wrong IV length: must be 16 bytes long

看来,如果我分配例如1024个字节Ť ○缓冲液,32字节大小的[]被发送到服务器,而是一个1024字节大小的[]将在服务器上生成:

Data packet found as [-55, 119, 34, -19, -33, -20, -67, -77, 54, -111, 14, 94, 73, 98, 34, -7, 0, 0, 0, 0, 0, 0,..................

我是否连上了正确的道路?

+0

发现了问题,我将编辑回答解决方案 –

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值