2016-04-27 54 views
0

我正在开发Android项目,我必须同时使用加密和解密方法。方案如下:在SignupActivity文本加密/解密方法Java

  1. 用户类型密码
  2. 用户的密码进行加密
  3. 在登录活动密码
  4. 从数据库中检索和解密方法被称为

我的问题是,在步骤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; 

    } 
+0

我的项目是一个密码管理器应用程序,保存用户密码并同时列出所有密码。那为什么我需要加密和解密。 我认为问题在于它总是为这两种方法生成不同的密钥 –

+0

Debug:十六进制转储密钥。你将如何安全地保存加密密钥?不要使用DES,它不再被认为是安全的,使用AES。 – zaph

回答

0

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

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

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