文本加密/解密方法Java



我正在研究Android项目,我必须同时使用加密和解密方法。 场景如下:

  1. 用户在"注册活动"中键入密码
  2. 用户的密码已加密
  3. 在登录活动中,从数据库中检索密码并调用解密方法

我的问题是在第 3 步中,它总是从解密返回 null。

代码示例:

注册活动:

    String name_data = name.getText().toString();
    String email_data = email.getText().toString();
    String password_data = password.getText().toString();
    password_data = enc.getEncryptedText(password_data);

登录活动

            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;
    }

首先,不要使用 DES,使用 AES。

您能做的最好的事情就是不保存密码。相反,请使用密码作为 AES 的密钥。这意味着您的用户必须在每次启动时输入密码,但这是最安全的解决方案。

如果必须在本地保存密码,则需要一致的密钥 - 代码每次调用函数都会生成一个新密钥。在注册时生成一个新密钥,并在共享首选项中使用固定密钥对其进行加密存储。

最新更新