我在vb.net中编写了代码,以加密内存流中的文件。我还解密文件,并将内存流复制到文件中以确保加密/解密有效。我的vb解决方案有效。
但是我需要使用Java解密。解密文件时,总是得到一个额外的“?”文件开头处的字符,但除此之外,重新调整是完美的。有人看过这样的东西吗?我必须承认,我的结果是仅使用一组数据,但是我已经两次使用新的密钥和向量对其进行了两次加密。
一些细节。我在vb中使用AES,PKCS7填充,在Java中使用PKCS5填充。该文件可以是任意长度。任何帮助表示赞赏。
我正在通过手机发布此信息,并且没有可用的代码。我明天可以添加。我只是希望这个描述能引起别人的注意。
谢谢,
SH
当我在VB中写入MemoryStream时,我这样声明了StreamWriter:
Writer = New IO.StreamWriter(MS, System.Text.Encoding.UTF8)
这是我的VB.NET加密功能。
Public Shared Function WriteEncryptedFile(ms As MemoryStream, FileName As String) As List(Of Byte())
Try
Dim original() As Byte
Dim myAes As System.Security.Cryptography.Aes = Aes.Create()
myAes.KeySize = 128
myAes.Padding = PadMode
Dim keys As New List(Of Byte())
keys.Add(myAes.Key)
keys.Add(myAes.IV)
original = ms.ToArray
Dim encryptor As ICryptoTransform = myAes.CreateEncryptor(myAes.Key, myAes.IV)
Using FileEncrypt As New FileStream(FileName, FileMode.Create, FileAccess.Write)
Using csEncrypt As New CryptoStream(FileEncrypt, encryptor, CryptoStreamMode.Write)
csEncrypt.Write(original, 0, original.Length)
csEncrypt.FlushFinalBlock()
FileEncrypt.Flush()
FileEncrypt.Close()
csEncrypt.Close()
End Using
End Using
Return keys
Catch e As Exception
MsgBox("Error during encryption." & vbCrLf & e.Message)
End Try
Return Nothing
End Function
这是Java解密:
public static void DecryptLIGGGHTSInputFile(String fileIn, String fileOut, String base64Key, String base64IV) throws Exception
{
// Get the keys from base64 text
byte[] key = Base64.decodeBase64(base64Key);
byte[] iv= Base64.decodeBase64(base64IV);
// Read fileIn into a byte[]
int len = (int)(new File(fileIn).length());
byte[] cipherText = new byte[len];
FileInputStream bs = new FileInputStream(fileIn);
bs.read(cipherText, 1, len-1);
System.out.println(cipherText.length);
System.out.println((double)cipherText.length/128);
bs.close();
// Create an Aes object
// with the specified key and IV.
Cipher cipher = null;
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
// Encrypt the message.
SecretKey secret = new SecretKeySpec(key, "AES");
/*
cipher.init(Cipher.ENCRYPT_MODE, secret, ivspec);
cipherText = cipher.doFinal("Hello, World!".getBytes("UTF-8"));
System.out.println(cipherText);
*/
cipher.init(Cipher.DECRYPT_MODE, secret , new IvParameterSpec(iv));
String plaintext = new String(cipher.doFinal(cipherText), "UTF-8");
System.out.println(plaintext.length());
FileWriter fw = new FileWriter(fileOut);
fw.write(plaintext);
fw.close();
}
最佳答案
这是一个BOM表问题。当我用VB创建MemoryStream时,我以UTF-8编码对其进行了初始化。我文件中的第一个字符将流的大小和位置从0字节增加到4字节,而该字符本来应该只有一个。解决方案是基于UTF-8创建不带字节顺序标记的编码,如下所示:
Dim UTF8EncodingWOBOM As New System.Text.UTF8Encoding(False) 'indicates to omit BOM
Writer = New IO.StreamWriter(MS, UTF8EncodingWOBOM)
我读过here,由于不推荐也不要求字节顺序标记,因此平台之间的编码不兼容性经常会出现问题。使用一个是不对的,使用一个是不对的。您基本上必须找到一种处理它们的方法。大量其他文章和帖子提出了不同的方法。要点是,要么识别它们,然后对它们进行处理(如果存在)。由于我对写作和阅读都有控制权,因此完全取消它们是很有意义的。
SH