我有一个用这段代码加密的文件(用于加密的C#代码):
public static byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes)
{
byte[] encryptedBytes = null;
// Set your salt here, change it to meet your flavor:
// The salt bytes must be at least 8 bytes.
byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
using (MemoryStream ms = new MemoryStream())
{
using (RijndaelManaged AES = new RijndaelManaged())
{
AES.KeySize = 256;
AES.BlockSize = 128;
var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
AES.Key = key.GetBytes(AES.KeySize / 8);
AES.IV = key.GetBytes(AES.BlockSize / 8);
AES.Mode = CipherMode.CBC;
using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
cs.Close();
}
encryptedBytes = ms.ToArray();
}
}
return encryptedBytes;
}
我有密码,我正在尝试在java中解密,但与C#相比,在java中无法理解如何执行此操作。 C#中有一些库我可以解密它,但我需要在java中这样做。要解密的文件是csv文件。
到目前为止,我在网上和其他一些工作中搜索到目前为止。如果我放入任何字符串代替“encryptedString”我可以解密就好了。所以我猜我的方法是不正确的,我应该只是解密文件而不是文件变成的字符串。但是如何实现呢?我在这里有一些代码,它也接受文件本身,将其转换为字节数组,然后尝试解密,代替字符串的字节。也没有得到解密来解决这个问题。如果有人可以帮助我,这将是非常有帮助的。
我的java代码:
File encryptedFile = getFileTodecrypt();
byte[] salt = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec spec = new PBEKeySpec(PASSWORD.toCharArray(), salt, 1000, 256);
SecretKey tmp = factory.generateSecret(spec);
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
/* Encrypt the message. */
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secret);
AlgorithmParameters params = cipher.getParameters();
byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
File fileToDecrypt = getFileTodecrypt(); // this gets my file
InputStream inputStream = FileUtils.openInputStream(fileToDecrypt);
byte[] bytesToBeDecrypted = IOUtils.toByteArray(inputStream);
// file bytes does not work
//byte[] ciphertext = cipher.doFinal(bytesToBeDecrypted);
// file to string does not work
//byte[] ciphertext = cipher.doFinal(encryptedString.getBytes("UTF-8"));
// this works, but does not take c# code into account at all
byte[] ciphertext = cipher.doFinal("hello".getBytes("UTF-8"));
IvParameterSpec iv2 = new IvParameterSpec(iv);
//decrypt
cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));
String plaintext = new String(cipher.doFinal(ciphertext), "UTF-8");
System.out.println(plaintext);
}
private String convertFileToString(File encryptedFile) throws IOException {
String fileString = FileUtils.readFileToString(encryptedFile, "UTF-8");
return fileString;
}