在客户端生成初始化向量,对消息进行加密,并与解密向量一起发送到服务。 Java AES加密-在客户端和服务器之间发送初始化向量
客户端代码:
String key1='1234567812345678 ';
byte[] key2=key1.getBytes (;
secretkeyspecsecret=newsecretkeyspec (key 2,' AES ';
cipher cipher=cipher.getinstance (AES/CBC/pkcs 5填充);
cipher.init (cipher.encrypt _ mode,secret );
byte [ ] encrypted=cipher.do final (msg.getbytes ) Standardcharsets.utf_8);
byte[] iv=cipher.getIV (;
string text=datatype converter.print base64 binary (加密;
system.out.println (加密信息: ) text );
byte buf=byte buffer.allocate (1024;
bytebuf.clear (;
//send iv
bytebuf.put(iv;
bytebuf.flip (;
while(bytebuf.hasremaining () ) )。
nbytes=client.write(bytebuf;
system.out.println('ivsent!' );
}
bytebuf.clear (;
bytebuf.put(text.getbytes ) );
bytebuf.flip (;
while(bytebuf.hasremaining () ) )。
nbytes=client.write(bytebuf;
}
服务器代码
logger.info (确认写入);
byte[] iv=buf.array (;
Logger.info(datapacketfoundas ),iv );
logger.info (确认写入);
字符串数据=new string (buf.array ) );
logger.info (数据分组基础)、数据);
ivparameterspecivspec=newivparameterspec (iv;
String key1='1234567812345678 ';
byte[] key2=key1.getBytes (;
secretkeyspecsecret=newsecretkeyspec (key 2,' AES ';
cipher cipher=cipher.getinstance (AES/CBC/pkcs 5填充);
cipher.init (cipher.decrypt _ mode,secret,ivspec );
byte [ ] encrypted=datatype converter.parse base64 binary (数据;
byte [ ] decrypted=cipher.do final (encrypted );
system.out.println (decrypted info : ) new string (decrypted,StandardCharsets.UTF_8) );
我得到了以下异常:
Java.security.invalidalgorithmparameterexception 3360 wrongivlength : must be 16 bytes long
例如,如果分配1024字节缓冲区,则可能会向服务器发送32字节大小的[],并在服务器上生成1024字节大小的[]。
datapacketfoundas [-55、119、34、-19、-33、-20、-67、-67、54、- 111、14、94、73、98、34、- 7、0、0……
我连接着正确的道路吗?
0
发现问题。 编辑答案解决方案