加密和解密android中的字符串

时间:2011-06-23 01:10:06

标签: android

嗨我想加密android中的字符串以便存储,稍后显示我必须解密它。是否有可能在android中进行md5散列或任何其他散列。 请给我举个例子。

6 个答案:

答案 0 :(得分:4)

答案 1 :(得分:3)

javax.crypto包可以完成您需要的一切

http://developer.android.com/reference/javax/crypto/package-summary.html

答案 2 :(得分:2)

android.util.Base64编码就足够了,如果你想存储一些东西,例如在共享首选项文件中:

以下是我的工作:

储存:

public void saveSomeText (String text) {
    SharedPreferences.Editor editor = prefs.edit();
    if (Utils.isEmpty( text ))
        text = null;
    else
        text = Base64.encodeToString( text.getBytes(), Base64.DEFAULT );
    editor.putString( "some_text", text );
    editor.commit();
}

检索:

public String getSomeText () {
    String text = prefs.getString( "some_text", null );
    if (!Utils.isEmpty( passwd )) {
        text = new String( Base64.decode( text, Base64.DEFAULT ) );
    }
    return text;
}

答案 3 :(得分:0)

使用MAHEncryptorLibrary

样品:

  • 用于加密

    MAHEncryptor mahEncryptor = MAHEncryptor.newInstance("This is sample SecretKeyPhrase");
    String encrypted = mahEncryptor.encode("This is MAHEncryptorLib java sample");
    
  • 用于解密

    MAHEncryptor mahEncryptor = MAHEncryptor.newInstance("This is sample SecretKeyPhrase");
    String decrypted = mahEncryptor.decode("4Vi86K/JL9gKclQahacrKLrEZL6/0vOpS4yPVm1hSLhhDsCMJTyd4A==");
    

答案 4 :(得分:-1)

当你想要在一侧加密一个字符串并在另一侧解密时,使用这个代码就可以正常工作。只需复制这段代码并在你的eclipse中运行,它就能解决你的问题

字符串的加密方法

    final int shift_key = 4; //it is the shift key to move charcter, like if i have 'a' then a=97+4=101 which =e and thus it changes
    String plainText = "adhami piran"; 
    char character; 
     char ch[]=new char[plainText.length()];//for storing encrypt char
   for (int iteration = 0; iteration < plainText.length(); iteration++)
            {
                    character = plainText.charAt(iteration); //get characters
                    character = (char) (character + shift_key); //perform shift
              }     ch[iteration]=character;//assign char to char array
     String encryptstr = String.valueOf(ch);//converting char array to string
     Toast.makeText(this, "Encrypt string is "+ encryptstr Toast.LENGTH_LONG).show();

字符串的解密方法

   for(int i=0;i<encryptstr.length();i++)
     {
        character=str.charAt(i);
        character = (char) (character -shift_key); //perform shift
            ch[i]=character;
     }
 Stirng decryptstr = String.valueOf(ch);
     Toast.makeText(this, "Decrypted String is "+decryptstr, Toast.LENGTH_LONG).show();

答案 5 :(得分:-2)

阅读这篇文章here->(How_to_encrypt_and_decrypt_strings.rhtml)。这几乎是你想要的。那里的技术使用.getInstance("AES");如果你想MD5只用MD5替换AES。