我尝试过用PBEwithMD5andDES加密字符串的不同方法,我用Bouncy Castle实现了它,但它似乎也不起作用,因为它返回与Java版本相比不同的字符串,所有参数都是相同的(密码,盐两个版本(C#和Java)中的迭代次数。
private IBufferedCipher makePbeCipherWithParam(
string algorithm,
bool forEncryption,
char[] password,
byte[] salt,
int iterationCount)
{
Asn1Encodable algParams = PbeUtilities.GenerateAlgorithmParameters(
algorithm, salt, iterationCount);
ICipherParameters cipherParams = PbeUtilities.GenerateCipherParameters(
algorithm, password, algParams);
IBufferedCipher cipher = (IBufferedCipher)PbeUtilities.CreateEngine(algorithm);
cipher.Init(forEncryption, cipherParams);
return cipher;
}
public string StringToPBEWithMD5AndDES(string rawString) {
char[] password = "APASSWORD".ToCharArray();
byte[] salt = { .... };
IBufferedCipher cEnc = makePbeCipherWithParam(
"PBEwithMD5andDES-CBC",
true,
password,
salt,
1024);
byte[] encBytes = cEnc.DoFinal(Hex.Decode(rawString));
string encodedUser = Encoding.UTF8.GetString(encBytes, 0, encBytes.Length);//encBytes.ToString();
Debug.WriteLine("Encoded user from StringToPBEWithMD5AndDES: " + encodedUser);
return encodedUser;
}
这是我试图复制的java版本
public class Utils {
private Cipher ecipher;
public Utils() {
String passPhrase = "PASSWORD";
byte[] salt = { ...};
int iterationCount = 1024;
try {
KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt,iterationCount);
SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
ecipher = Cipher.getInstance(key.getAlgorithm());
dcipher = Cipher.getInstance(key.getAlgorithm());
AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);
ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
} catch (InvalidAlgorithmParameterException e) {
System.out.println("EXCEPTION: InvalidAlgorithmParameterException");
} catch (InvalidKeySpecException e) {
System.out.println("EXCEPTION: InvalidKeySpecException");
} catch (NoSuchPaddingException e) {
System.out.println("EXCEPTION: NoSuchPaddingException");
} catch (NoSuchAlgorithmException e) {
System.out.println("EXCEPTION: NoSuchAlgorithmException");
} catch (InvalidKeyException e) {
System.out.println("EXCEPTION: InvalidKeyException");
}
}
public String encrypt(String str) {
try {
byte[] utf8 = str.getBytes("UTF-8");
byte[] enc = ecipher.doFinal(utf8);
return new String(Base64.encodeBase64(enc), "UTF-8");
} catch (BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
} catch (Exception e) {
}
return null;
}
}