0
我正在开发Android项目,我必须同时使用加密和解密方法。方案如下:在SignupActivity文本加密/解密方法Java
- 用户类型密码
- 用户的密码进行加密 在登录活动密码
- 从数据库中检索和解密方法被称为
我的问题是,在步骤3它总是从解密中返回null。
代码示例:
SignUpActivity:
String name_data = name.getText().toString();
String email_data = email.getText().toString();
String password_data = password.getText().toString();
password_data = enc.getEncryptedText(password_data);
LoginActivity
String password_in_database = helper.searchPassword(email_data);
password_in_database = enc.getDecryptedText(password_in_database);
加密/解密类
public class EncryptDecryptStringWithDES {
public static Cipher ecipher;
public static Cipher dcipher;
public static SecretKey key;
public static String getEncryptedText(String sty) throws Exception {
// generate secret key using DES algorithm
key = KeyGenerator.getInstance("DES").generateKey();
ecipher = Cipher.getInstance("DES");
// initialize the ciphers with the given key
ecipher.init(Cipher.ENCRYPT_MODE, key);
sty = encrypt(sty);
return sty;
}
public static String getDecryptedText(String sty) throws Exception {
key = KeyGenerator.getInstance("DES").generateKey();
dcipher = Cipher.getInstance("DES");
dcipher.init(Cipher.DECRYPT_MODE, key);
sty = decrypt(sty);
return sty;
}
public static String encrypt(String str) {
try {
// encode the string into a sequence of bytes using the named charset
// storing the result into a new byte array.
byte[] utf8 = str.getBytes("UTF8");
byte[] enc = ecipher.doFinal(utf8);
// encode to base64
enc = BASE64EncoderStream.encode(enc);
return new String(enc);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String decrypt(String str) {
try {
// decode with base64 to get bytes
byte[] dec = BASE64DecoderStream.decode(str.getBytes());
byte[] utf8 = dcipher.doFinal(dec);
// create new string based on the specified charset
return new String(utf8, "UTF8");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
我的项目是一个密码管理器应用程序,保存用户密码并同时列出所有密码。那为什么我需要加密和解密。 我认为问题在于它总是为这两种方法生成不同的密钥 –
Debug:十六进制转储密钥。你将如何安全地保存加密密钥?不要使用DES,它不再被认为是安全的,使用AES。 – zaph