C#/Java | AES256加密/解密
我想对通过Java/C#sockets(Java服务器、C#客户端)发送的所有数据进行加密。 我想使用AES256,但我无法让Java和C生成相同的加密代码。谁能给我举两个例子,一个是Java,一个是C#,它们生成相同的结果并正确地解密结果 到目前为止,我尝试的是:C#/Java | AES256加密/解密,c#,java,encryption,aes,C#,Java,Encryption,Aes,我想对通过Java/C#sockets(Java服务器、C#客户端)发送的所有数据进行加密。 我想使用AES256,但我无法让Java和C生成相同的加密代码。谁能给我举两个例子,一个是Java,一个是C#,它们生成相同的结果并正确地解密结果 到目前为止,我尝试的是: public Encrypt(AOBCore instance){ try { String message="This is just an example"; // Get the
public Encrypt(AOBCore instance){
try {
String message="This is just an example";
// Get the KeyGenerator
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(256); // 192 and 256 bits may not be available
// Generate the secret key specs.
SecretKey skey = kgen.generateKey(); //Cantget 'test' in here...
byte[] raw = skey.getEncoded();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
// Instantiate the cipher
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted =
cipher.doFinal(message.getBytes());
System.out.println("encrypted string: " + asHex(encrypted));
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] original =
cipher.doFinal(encrypted);
String originalString = new String(original);
System.out.println("Original string: " +
originalString + " " + asHex(original));
} catch (Exception e) {
instance.logMessage(e.getMessage());
}
}
public static String asHex (byte buf[]) {
StringBuffer strbuf = new StringBuffer(buf.length * 2);
int i;
for (i = 0; i < buf.length; i++) {
if (((int) buf[i] & 0xff) < 0x10)
strbuf.append("0");
strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
}
return strbuf.toString();
}
问题是您没有在Java代码中指定密码或填充。这将使用算法默认值,当需要与其他库的互操作性时,您永远不希望这样做。像这样初始化您的
密码
:
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
根据答案,Java中的PKCS5应该与.Net中的PKCS7兼容。由于您明智地使用了CBC,因此需要修改代码以使用相同的初始化向量进行加密和解密。您应该而不是为此使用密钥。静脉注射应该是随机产生的。通过调用Cipher.getIV()
,您可以使用JavaCipher
为加密生成的IV
此外,注意与评论中提到的字符编码保持一致。您应该展示您迄今为止的尝试-这不是一个代码工厂,互联网提供了大量示例。添加了我尝试的内容。。。不,我找不到关于C#/Java示例的很多信息。看起来你确实有同样的问题。有了这个密码,我得到了uZ▀pE÷R~JÙ‗(tÄÒ6美元)~∟\¸¸(À)5ÒZêL♣ 用普通测试和通过测试
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");