分类: Android2013-06-24 11:25 328人阅读 评论(3) 收藏 举报

  

  密码学中的高级加密标准(Advanced Encryption Standard,AES),又称高级加密标准Rijndael加密法,是美国联邦政府采用的一种区块加密标准。这个标准用来替代原先的DES,已经被多方分析且广为全世界所使用。该算法为比利时密码学家Joan Daemen和Vincent Rijmen所设计,结合两位作者的名字,以Rijndael之命名之。

要区别4.2以上版本的调用方法,否则将会出现意想不到的问题。

AESCipher.java

  1. package com.test;
  2. import java.security.SecureRandom;
  3. import javax.crypto.Cipher;
  4. import javax.crypto.KeyGenerator;
  5. import javax.crypto.SecretKey;
  6. import javax.crypto.spec.SecretKeySpec;
  7. public class AESCipher {
  8. public static String encrypt(String key, String src) throws Exception {
  9. byte[] rawKey = getRawKey(key.getBytes());
  10. byte[] result = encrypt(rawKey, src.getBytes());
  11. return toHex(result);
  12. }
  13. public static String decrypt(String key, String encrypted) throws Exception {
  14. byte[] rawKey = getRawKey(key.getBytes());
  15. byte[] enc = toByte(encrypted);
  16. byte[] result = decrypt(rawKey, enc);
  17. return new String(result);
  18. }
  19. private static byte[] getRawKey(byte[] seed) throws Exception {
  20. KeyGenerator kgen = KeyGenerator.getInstance("AES");
  21. // SHA1PRNG 强随机种子算法, 要区别4.2以上版本的调用方法
  22. SecureRandom sr = null;
  23. if (android.os.Build.VERSION.SDK_INT >=  17) {
  24. sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
  25. } else {
  26. sr = SecureRandom.getInstance("SHA1PRNG");
  27. }
  28. sr.setSeed(seed);
  29. kgen.init(256, sr); //256 bits or 128 bits,192bits
  30. SecretKey skey = kgen.generateKey();
  31. byte[] raw = skey.getEncoded();
  32. return raw;
  33. }
  34. private static byte[] encrypt(byte[] key, byte[] src) throws Exception {
  35. SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
  36. Cipher cipher = Cipher.getInstance("AES");
  37. cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
  38. byte[] encrypted = cipher.doFinal(src);
  39. return encrypted;
  40. }
  41. private static byte[] decrypt(byte[] key, byte[] encrypted) throws Exception {
  42. SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
  43. Cipher cipher = Cipher.getInstance("AES");
  44. cipher.init(Cipher.DECRYPT_MODE, skeySpec);
  45. byte[] decrypted = cipher.doFinal(encrypted);
  46. return decrypted;
  47. }
  48. public static String toHex(String txt) {
  49. return toHex(txt.getBytes());
  50. }
  51. public static String fromHex(String hex) {
  52. return new String(toByte(hex));
  53. }
  54. public static byte[] toByte(String hexString) {
  55. int len = hexString.length()/2;
  56. byte[] result = new byte[len];
  57. for (int i = 0; i < len; i++)
  58. result[i] = Integer.valueOf(hexString.substring(2*i, 2*i+2), 16).byteValue();
  59. return result;
  60. }
  61. public static String toHex(byte[] buf) {
  62. if (buf == null)
  63. return "";
  64. StringBuffer result = new StringBuffer(2*buf.length);
  65. for (int i = 0; i < buf.length; i++) {
  66. appendHex(result, buf[i]);
  67. }
  68. return result.toString();
  69. }
  70. private final static String HEX = "0123456789ABCDEF";
  71. private static void appendHex(StringBuffer sb, byte b) {
  72. sb.append(HEX.charAt((b>>4)&0x0f)).append(HEX.charAt(b&0x0f));
  73. }
  74. }

TestAES.java

  1. package com.test;
  2. import android.app.Activity;
  3. import android.os.Bundle;
  4. import android.view.View;
  5. import android.view.View.OnClickListener;
  6. import android.widget.Button;
  7. import android.widget.EditText;
  8. import android.widget.TextView;
  9. public class TestAES extends Activity implements OnClickListener {
  10. private TextView tvTip = null;
  11. private EditText etKey = null;
  12. private EditText etStr = null;
  13. private Button btnEncrypt = null;
  14. private Button btnDecrypt = null;
  15. //
  16. String src = null;
  17. String key = null;
  18. String dest = null;
  19. /** Called when the activity is first created. */
  20. @Override
  21. public void onCreate(Bundle savedInstanceState) {
  22. super.onCreate(savedInstanceState);
  23. setContentView(R.layout.main);
  24. tvTip = (TextView) findViewById(R.id.tvTip);
  25. etKey = (EditText) findViewById(R.id.etKey);
  26. etStr = (EditText) findViewById(R.id.etStr);
  27. btnEncrypt = (Button) findViewById(R.id.btnEncrypt);
  28. btnEncrypt.setOnClickListener(this);
  29. btnDecrypt = (Button) findViewById(R.id.btnDecrypt);
  30. btnDecrypt.setOnClickListener(this);
  31. btnEncrypt.setEnabled(true);
  32. btnDecrypt.setEnabled(false);
  33. }
  34. @Override
  35. public void onClick(View v) {
  36. // TODO Auto-generated method stub
  37. if (v == btnEncrypt) {
  38. src = etStr.getText().toString().trim();
  39. key = etKey.getText().toString().trim();
  40. if (!src.equals("") && !key.equals("")) {
  41. try {
  42. dest = AESCipher.encrypt(key, src);
  43. tvTip.setText("Encrypted:");
  44. etStr.setText(dest);
  45. btnEncrypt.setEnabled(false);
  46. btnDecrypt.setEnabled(true);
  47. } catch (Exception e) {
  48. // TODO Auto-generated catch block
  49. e.printStackTrace();
  50. }
  51. }
  52. } else if (v == btnDecrypt) {
  53. src = etStr.getText().toString().trim();
  54. key = etKey.getText().toString().trim();
  55. if (!src.equals("") && !key.equals("")) {
  56. try {
  57. dest = AESCipher.decrypt(key, src);
  58. tvTip.setText("Decrypted:");
  59. etStr.setText(dest);
  60. btnDecrypt.setEnabled(false);
  61. btnEncrypt.setEnabled(true);
  62. } catch (Exception e) {
  63. // TODO Auto-generated catch block
  64. e.printStackTrace();
  65. }
  66. }else{
  67. tvTip.setText("Source:");
  68. btnDecrypt.setEnabled(false);
  69. btnEncrypt.setEnabled(true);
  70. }
  71. }
  72. }
  73. }

main.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="fill_parent"
  4. android:layout_height="fill_parent"
  5. android:orientation="vertical" >
  6. <LinearLayout
  7. android:layout_width="fill_parent"
  8. android:layout_height="wrap_content"
  9. android:orientation="vertical" >
  10. <TextView
  11. android:layout_width="100dp"
  12. android:layout_height="wrap_content"
  13. android:text="Key:" />
  14. <EditText
  15. android:id="@+id/etKey"
  16. android:layout_width="200dp"
  17. android:layout_height="40dp"
  18. android:maxLength="32"
  19. android:hint="Input the key" />
  20. </LinearLayout>
  21. <LinearLayout
  22. android:layout_width="fill_parent"
  23. android:layout_height="wrap_content"
  24. android:orientation="vertical" >
  25. <TextView
  26. android:id="@+id/tvTip"
  27. android:layout_width="100dp"
  28. android:layout_height="wrap_content"
  29. android:text="Source:" />
  30. <EditText
  31. android:id="@+id/etStr"
  32. android:layout_width="400dp"
  33. android:layout_height="200dp"
  34. android:hint="Input the source"
  35. android:inputType="textMultiLine"
  36. android:maxLength="4096"
  37. android:maxLines="100"
  38. android:scrollHorizontally="false" />
  39. </LinearLayout>
  40. <LinearLayout
  41. android:layout_width="fill_parent"
  42. android:layout_height="wrap_content"
  43. android:orientation="horizontal" >
  44. <Button
  45. android:id="@+id/btnEncrypt"
  46. android:layout_width="120dp"
  47. android:layout_height="50dp"
  48. android:text="加密字符串" />
  49. <Button
  50. android:id="@+id/btnDecrypt"
  51. android:layout_width="120dp"
  52. android:layout_height="50dp"
  53. android:text="解密字符串" />
  54. </LinearLayout>
  55. </LinearLayout>

AES加解密算法在Android中的应用及Android4.2以上版本调用问题的更多相关文章

  1. AES加解密算法Qt实现

    [声明] (1) 本文源码 在一位未署名网友源码基础上,利用Qt编程,实现了AES加解密算法,并添加了文件加解密功能.在此表示感谢!该源码仅供学习交流,请勿用于商业目的. (2) 图片及描述 除图1外 ...

  2. AES加解密算法

    直接粘代码,该类是基于微信公众号消息加密解密所提供的PHP DEMO改造而来,目前使用于彬彬大学APP接口token校验中. php的mcrypt 扩展已经过时了大约10年,并且用起来很复杂.因此它被 ...

  3. 最强加密算法?AES加解密算法Matlab和Verilog实现

    目录 背景 AES加密的几种模式 基本运算 AES加密原理 Matlab实现 Verilog实现 Testbench 此本文首发于公众号[两猿社],重点讲述了AES加密算法的加密模式和原理,用MATL ...

  4. 【加解密专辑】对接触到的PGP、RSA、AES加解密算法整理

    先贴代码,有空再整理思路 PGP加密 using System; using System.IO; using Org.BouncyCastle.Bcpg; using Org.BouncyCastl ...

  5. Aes 加解密算法

    public class AesHelper    {        /// <summary>        /// 生成128位的随机AES秘钥        /// </sum ...

  6. PHP完整的AES加解密算法使用及例子(256位)

    依赖PHP自身的mcrypt扩展 <?php class aes { // CRYPTO_CIPHER_BLOCK_SIZE 32 private $_secret_key = 'default ...

  7. C#与java中的AES加解密互解算法

    一.C#版AES加解密算法 public class AESCode { public string Key { get; set; } public string Encrypt(string va ...

  8. RSA,AES加解密算法的实现

    目录 Python实现RSA公钥加密算法 RSA公钥加密算法原理 RSA算法的Python实现 AES加解密算法实现 AES加解密算法原理 AES加解密算法Python实现 参考文献 Python实现 ...

  9. Java中的AES加解密工具类:AESUtils

    本人手写已测试,大家可以参考使用 package com.mirana.frame.utils.encrypt; import com.mirana.frame.constants.SysConsta ...

随机推荐

  1. MySQL保存或更新 saveOrUpdate

    1. 引子 在项目开发过程中,有一些数据在写入时候,若已经存在,则覆盖即可.这样可以防止多次重复写入唯一键冲突报错.下面先给出两个MyBatis配置文件中使用saveOrUpdate的示例 <! ...

  2. emulator: ERROR: x86 emulation currently requires hardware acceleration!Please ensure Intel HAXM is properly installed and usable.CPU acceleration status: HAX kernel module is not installed!

    Android Studio 1.0 已经放出来了,以后的Android平台开发激昂逐步从Eclipse向Android Studio迁移,为了能不落伍我也特意从Google下载了Android St ...

  3. [转载]angular通过$http与服务器通信

    转载自:http://www.cooklife.cn/detail/54c5044ec93620284e964b58#View angular是一个前端框架,实现了可交互式的页面,但是对于一个web应 ...

  4. Java 抽象类和抽象方法

    包含抽象方法的类叫抽象类,如果一个类中包含一个或多个抽象方法,该类必须被限定为抽象的,否则编译器会报错,抽象类不可创建对象,创建抽象类的对象编译器会报错 如果从一个抽象类继承,并想创建该新类的对象,那 ...

  5. pycharm+PyQt5+python最新开发环境配置

    Python 3.6https://www.python.org/downloads/windows/========================================PyQt5 pip ...

  6. 193 Valid Phone Numbers

    Given a text file file.txt that contains list of phone numbers (one per line), write a one liner bas ...

  7. hdu 1232 变成生成树至少还要加几条边 (并查集模板题)

    求一个图 变成生成树至少还要加几条边(成环的边要删掉,但不用统计) Sample Input4 2 //n m1 3//u v4 33 31 21 32 35 21 23 5999 00 Sample ...

  8. 开源项目TypeScript

    TypeScript 优秀开源项目大合集   TypeScript出来有段时间了,也冒出了很多用TypeScript开发的优秀开源项目,搜寻了一些基于TypeScript项目,分享给大家: https ...

  9. 将 Ubuntu 16.04 LTS 升级到 Ubuntu 18.04 LTS

    将 Ubuntu 16.04 LTS 升级到 Ubuntu 18.04 LTS   Ubuntu 18.04 LTS(Bionic Beaver)即将发布, 如果您正在使用Ubuntu 16.04LT ...

  10. ubuntun 18.04 desktop安装jupyter-notebook

    在ubuntu18.04要安装jupyter-notebook,当然前提是先安装python,然后按如下步骤安装jupyter-notebook,现在记录如下: 1.sudo apt-get upda ...