我正在尝试解密使用Microsoft CryptoAPI的CryptEncrypt函数加密的Java文件。我已经读过“返回的加密块缓冲区是按低位字节序排列的(与Java和.NET的高位字节序相比)。”
我正在Java中使用ByteBuffer和ByteOrder类,并且可以肯定我做错了,因为无论尝试什么,我都使用System.out.println获得前字节和后字节的相同打印输出。
byte [] beforebytes = null;
// code to extract bytes from file here
ByteBuffer bb = ByteBuffer.wrap(beforebytes);
bb.order( ByteOrder.LITTLE_ENDIAN); // BIG_ENDIAN doesn't work either?
ByteBuffer slice = bb.slice();
// 'slice' now refers to the same data, but is supposed to be BIG ENDIAN
byte[] afterbytes = new byte[bb.capacity()];
// transfer bytes from this buffer into the given destination array
slice.get(afterbytes, 0, afterbytes.length);
任何帮助将不胜感激!
谢谢,Bertrand
我用C解决了这个问题! Java现在可以正确解密由CryptoAPI加密的内容。
我从CryptoAPI示例开始于:http://blogs.msdn.com/b/alejacma/archive/2008/01/28/how-to-generate-key-pairs-encrypt-and-decrypt-data-with-cryptoapi.aspx
然后在将加密的文本写入文件之前,我添加了一个参考代码块CryptoAPI C++ interop with Java using AES
// reverse bytes of pbData for java
for (unsigned i = 0; i<dwEncryptedLen / 2; i++)
{
BYTE temp = pbData[i];
pbData[i] = pbData[dwEncryptedLen - i - 1];
pbData[dwEncryptedLen - i - 1] = temp;
}
此参考适用于AES,但我使用RSA加密。对于解密,我使用了使用算法“ RSA / NONE / PKCS1Padding”的bouncycastle提供程序。要在Windows 7上安装bouncycastle提供程序,请遵循:http://sce.uhcl.edu/yang/teaching/JDK_JCE_environment_Configuration.htm和reboot!
希望这会帮助某人。
如果从缓冲区中取出单个字节(或字节数组),则字节顺序无关紧要。仅在从缓冲区中获取16位短值或32位整数值时才重要;在这种情况下,缓冲区中的字节将根据字节顺序进行适当交换。
例如:
ByteBuffer buf1 = ByteBuffer.wrap(new byte[]{0x01, 0x02, 0x03, 0x04});
buf1.order(ByteOrder.LITTLE_ENDIAN);
int n1 = buf1.getInt();
System.out.println(n1 == 0x04030201);
ByteBuffer buf2 = ByteBuffer.wrap(new byte[]{0x01, 0x02, 0x03, 0x04});
buf2.order(ByteOrder.BIG_ENDIAN);
int n2 = buf2.getInt();
System.out.println(n2 == 0x01020304);
尝试执行您的代码时出现错误:
error: cannot find symbol
buf.order(ByteOrder.LITTLE_ENDIAN);
^
symbol: variable ByteOrder
location: class GDC