使用C#CryptoStream的Java equilavent加密和解密字符串
我正在考虑在Java中开发移动平台操作系统的应用程序。
I am looking at developing an application in Java for a mobile platform operating system.
我已经在Windows环境的C#WPF中开发了一个应用程序。我正在使用cryptostream来加密和解密字符串使用以下代码。下面显示的代码是仅加密
I have developed an application in C# WPF for the Windows Environment. I am using a cryptostream in order to encrypt and decrypt a string using the following code. the code shown below is the encryption only
public string encrypt(string encryptionString)
{
byte[] clearTextBytes = Encoding.UTF8.GetBytes(encryptionString);
SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();
MemoryStream ms = new MemoryStream();
byte[] rgbIV = Encoding.ASCII.GetBytes("ryojvlzmdalyglrj");
byte[] key = Encoding.ASCII.GetBytes("hcxilkqbbhczfeultgbskdmaunivmfuo");
CryptoStream cs = new CryptoStream(ms, rijn.CreateEncryptor(key, rgbIV), CryptoStreamMode.Write);
cs.Write(clearTextBytes, 0, clearTextBytes.Length);
cs.Close();
return Convert.ToBase64String(ms.ToArray());
}
加密的字符串存储在在线数据库中。我需要做的是让Java应用程序能够从数据库中读取字符串,并使用与C#应用程序相同的加密密钥对字符串进行解密。
The encrypted string is stored in an online database. What I need to be able to do is for the java application to be able to read the string from the database and decrypt the string using the same encryption keys from the C# application.
感谢您的帮助
个人而言,我喜欢 BouncyCastle 用于Java加密。这个代码(使用BouncyCastle轻量级API)应该做的诀窍:
Personally, I like BouncyCastle for Java crypto. This code (using the BouncyCastle lightweight API) should do the trick:
String decrypt(byte[] cryptoBytes, byte[] key, byte[] iv) {
BlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()));
cipher.init(false, new ParametersWithIV(new KeyParameter(key), iv));
byte[] out = new byte[cipher.getOutputSize(cryptoBytes.length)];
int offset = cipher.processBytes(cryptoBytes, 0, cryptoBytes.length, out, 0);
cipher.doFinal(out, offset);
return new String(out);
}
我发现BouncyCastle的轻量级API比JCE提供者的东西不那么痛苦,但你可以使用它作为提供者,如果你愿意。
I find BouncyCastle's lightweight API to be less painful than the JCE provider stuff but you can use it as a provider if you wish.
它看起来像.net SymmetricAlgorithm
和BC的 PaddedBufferedBlockCipher
默认为PKCS7填充,所以你应该可以使用默认值。
It looks like both the .net SymmetricAlgorithm
and BC's PaddedBufferedBlockCipher
default to PKCS7 padding so you should be OK with using the defaults.