我有一個C#應用程序來調用Java Web服務來驗證用戶的密碼。我想讓C#應用程序加密密碼,然後讓Java Web服務解密密碼。我已經完成了Java方面的代碼(解密代碼),但我無法弄清楚C#代碼來加密代碼。C#(加密)和Java(解密)之間的AES加密/解密
這是我的Java代碼...
public void validateUserPassword(String encryptedPassword) {
String algorithm = "AES";
SecretKeySpec keySpec = null;
byte[] key = "<==OMGWTFBBQ!==>".getBytes();
Cipher cipher = null;
cipher = Cipher.getInstance(algorithm);
keySpec = new SecretKeySpec(key, algorithm);
byte[] encryptionBytes = new sun.misc.BASE64Decoder().decodeBuffer(encryptedPassword);
cipher.init(Cipher.DECRYPT_MODE, keySpec);
byte[] recoveredBytes = cipher.doFinal(encryptionBytes);
String recovered = new String(recoveredBytes);
log.info("Encrypted password: " + encryptedPassword);
log.info("Dencrypted password: " + recovered);
}
這裏是我發現使用C#進行加密,但由於我的Java功能,所以我的Java Web服務是無法也不會產生相同的encrypion串解密它。
private void btnEncrypt_Click(object sender, EventArgs e)
{
string PlainText = "testing";
string Password = "<==OMGWTFBBQ!==>";
string Salt = "Kosher";
string HashAlgorithm = "SHA1";
int PasswordIterations = 2;
string InitialVector = "OFRna73m*aze01xY";
int KeySize = 256;
string encryptedPassword;
byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt);
byte[] PlainTextBytes = Encoding.UTF8.GetBytes(PlainText);
PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);
byte[] KeyBytes = DerivedPassword.GetBytes(KeySize/8);
RijndaelManaged SymmetricKey = new RijndaelManaged();
SymmetricKey.Mode = CipherMode.CBC;
byte[] CipherTextBytes = null;
using (ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes))
{
using (MemoryStream MemStream = new MemoryStream())
{
using (CryptoStream CryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write))
{
CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length);
CryptoStream.FlushFinalBlock();
CipherTextBytes = MemStream.ToArray();
MemStream.Close();
CryptoStream.Close();
}
}
}
SymmetricKey.Clear();
encryptedPassword = Convert.ToBase64String(CipherTextBytes);
MessageBox.Show("Encrypted password: " + encryptedPassword);
}
我不介意改變我的Java Web服務解密的方式,以使其與我的C#應用程序一起工作。
我是一個相當隨便SO用戶,我看問定期質詢的確切類型。請在SO中搜索以下內容:'aes c#java'或者現在您已經提出了該問題,請查看右欄中的相關問題。 –
@Eric J有700多個答案,我不太確定你是否有資格成爲休閒用戶;) – Nate
@Nate:也許我只是有一個Skeet自卑感。 –