我有一个由 apache wicket 构建的简单 Java Web 应用程序。当我在网络应用程序中注册用户时,我使用三元组加密他们输入的密码并将其保存到数据库中。在登录页面,当他们输入相同的密码时,我对其进行加密并将加密后的密码传递给数据库,以检查它是否正确。
现在我正在构建一个具有相同登录功能的安卓应用程序。
在 android 应用程序登录页面中,我使用相同的加密库来加密密码,并且我对两个平台使用相同的密钥和初始化向量,但是如果我尝试在 android 中输入相同的密码字符串,TripleDes 算法会生成完全不同的加密密码(很多更长)。因此从 android 设备登录失败。我还注意到android生成的加密密码无法解密,它会引发异常。
我认为两个平台之间可能存在字符串编码问题差异,但无法弄清楚是什么原因造成的以及如何解决它。
这是我使用的算法:
public class TripleDES {
private String key;
private byte[] initializationVector;
public TripleDES(String key, byte[] initializationVector)
{
this.key = key;
this.initializationVector = initializationVector;
}
public String encryptText(String plainText) throws Exception{
//---- Use specified 3DES key and IV from other source -------------------------
byte[] plaintext = plainText.getBytes();
byte[] tdesKeyData = key.getBytes();
System.out.println("plain text length: " + plaintext.length);
System.out.println("key length: " + tdesKeyData.length);
Cipher c3des = Cipher.getInstance("DESede/CBC/PKCS5Padding");
SecretKeySpec myKey = new SecretKeySpec(tdesKeyData, "DESede");
IvParameterSpec ivspec = new IvParameterSpec(initializationVector);
c3des.init(Cipher.ENCRYPT_MODE, myKey, ivspec);
byte[] cipherText = c3des.doFinal(plaintext);
return Base64Coder.encodeString(new String(cipherText));
}
public String decryptText(String encryptedText) throws Exception{
//---- Use specified 3DES key and IV from other source -------------------
byte[] enctext = Base64Coder.decode(encryptedText);
byte[] tdesKeyData = key.getBytes();
Cipher c3des = Cipher.getInstance("DESede/CBC/PKCS5Padding");
SecretKeySpec myKey = new SecretKeySpec(tdesKeyData, "DESede");
IvParameterSpec ivspec = new IvParameterSpec(initializationVector);
c3des.init(Cipher.DECRYPT_MODE, myKey, ivspec);
byte[] cipherText = c3des.doFinal(enctext);
return new String(cipherText);
}
}