在Android中加密/解密字符串的简便方法 [英] Easy way to Encrypt/Decrypt string in Android

查看:165
本文介绍了在Android中加密/解密字符串的简便方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是如何加密字符串:

String AndroidId;

@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.download_movie_activity);

  cancel = (Button)findViewById(R.id.img_cancle);

  linear= (LinearLayout)findViewById(R.id.progress);
  linear.setVisibility(View.GONE);

  String encrypted = "MzIyNTE2" + "OTQNzM4NTQ=";

  Log.e("Encrypt", encrypted);

  WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
  WifiInfo wInfo = wifiManager.getConnectionInfo();
  AndroidId = wInfo.getMacAddress();

  AndroidId=encrypted;

如何加密存储MAC地址的AndroidId.

How do i encrypt my AndroidId in which I storing a MAC address.

推荐答案

您可以使用

You can use Cipher for this.

此类提供用于加密和解密的加密密码功能.它构成了Java加密扩展(JCE)框架的核心.

This class provides the functionality of a cryptographic cipher for encryption and decryption. It forms the core of the Java Cryptographic Extension (JCE) framework.

加密和解密示例:

public static SecretKey generateKey() 
    throws NoSuchAlgorithmException, InvalidKeySpecException 
{ 
    return secret = new SecretKeySpec(password.getBytes(), "AES"); 
}

public static byte[] encryptMsg(String message, SecretKey secret)
    throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidParameterSpecException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException 
{ 
   /* Encrypt the message. */
   Cipher cipher = null; 
   cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
   cipher.init(Cipher.ENCRYPT_MODE, secret); 
   byte[] cipherText = cipher.doFinal(message.getBytes("UTF-8")); 
   return cipherText; 
}

public static String decryptMsg(byte[] cipherText, SecretKey secret) 
    throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidParameterSpecException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException 
{
    /* Decrypt the message, given derived encContentValues and initialization vector. */
    Cipher cipher = null;
    cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    cipher.init(Cipher.DECRYPT_MODE, secret); 
    String decryptString = new String(cipher.doFinal(cipherText), "UTF-8");
    return decryptString; 
}

要加密:

SecretKey secret = generateKey();
EncUtil.encryptMsg(String toEncrypt, secret))

要解密:

EncUtil.decryptMsg(byte[] toDecrypt, secret))

这篇关于在Android中加密/解密字符串的简便方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆