AES加解密算法在Android中的应用及Android4.2以上版本调用问题
AES加解密算法在Android中的应用及Android4.2以上版本调用问题
密码学中的高级加密标准(Advanced Encryption Standard,AES),又称高级加密标准Rijndael加密法,是美国联邦政府采用的一种区块加密标准。这个标准用来替代原先的DES,已经被多方分析且广为全世界所使用。该算法为比利时密码学家Joan Daemen和Vincent Rijmen所设计,结合两位作者的名字,以Rijndael之命名之。
要区别4.2以上版本的调用方法,否则将会出现意想不到的问题。
AESCipher.java
- package com.test;
- import java.security.SecureRandom;
- import javax.crypto.Cipher;
- import javax.crypto.KeyGenerator;
- import javax.crypto.SecretKey;
- import javax.crypto.spec.SecretKeySpec;
- public class AESCipher {
- public static String encrypt(String key, String src) throws Exception {
- byte[] rawKey = getRawKey(key.getBytes());
- byte[] result = encrypt(rawKey, src.getBytes());
- return toHex(result);
- }
- public static String decrypt(String key, String encrypted) throws Exception {
- byte[] rawKey = getRawKey(key.getBytes());
- byte[] enc = toByte(encrypted);
- byte[] result = decrypt(rawKey, enc);
- return new String(result);
- }
- private static byte[] getRawKey(byte[] seed) throws Exception {
- KeyGenerator kgen = KeyGenerator.getInstance("AES");
- // SHA1PRNG 强随机种子算法, 要区别4.2以上版本的调用方法
- SecureRandom sr = null;
- if (android.os.Build.VERSION.SDK_INT >= 17) {
- sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
- } else {
- sr = SecureRandom.getInstance("SHA1PRNG");
- }
- sr.setSeed(seed);
- kgen.init(256, sr); //256 bits or 128 bits,192bits
- SecretKey skey = kgen.generateKey();
- byte[] raw = skey.getEncoded();
- return raw;
- }
- private static byte[] encrypt(byte[] key, byte[] src) throws Exception {
- SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
- Cipher cipher = Cipher.getInstance("AES");
- cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
- byte[] encrypted = cipher.doFinal(src);
- return encrypted;
- }
- private static byte[] decrypt(byte[] key, byte[] encrypted) throws Exception {
- SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
- Cipher cipher = Cipher.getInstance("AES");
- cipher.init(Cipher.DECRYPT_MODE, skeySpec);
- byte[] decrypted = cipher.doFinal(encrypted);
- return decrypted;
- }
- public static String toHex(String txt) {
- return toHex(txt.getBytes());
- }
- public static String fromHex(String hex) {
- return new String(toByte(hex));
- }
- public static byte[] toByte(String hexString) {
- int len = hexString.length()/2;
- byte[] result = new byte[len];
- for (int i = 0; i < len; i++)
- result[i] = Integer.valueOf(hexString.substring(2*i, 2*i+2), 16).byteValue();
- return result;
- }
- public static String toHex(byte[] buf) {
- if (buf == null)
- return "";
- StringBuffer result = new StringBuffer(2*buf.length);
- for (int i = 0; i < buf.length; i++) {
- appendHex(result, buf[i]);
- }
- return result.toString();
- }
- private final static String HEX = "0123456789ABCDEF";
- private static void appendHex(StringBuffer sb, byte b) {
- sb.append(HEX.charAt((b>>4)&0x0f)).append(HEX.charAt(b&0x0f));
- }
- }
TestAES.java
- package com.test;
- import android.app.Activity;
- import android.os.Bundle;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.TextView;
- public class TestAES extends Activity implements OnClickListener {
- private TextView tvTip = null;
- private EditText etKey = null;
- private EditText etStr = null;
- private Button btnEncrypt = null;
- private Button btnDecrypt = null;
- //
- String src = null;
- String key = null;
- String dest = null;
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- tvTip = (TextView) findViewById(R.id.tvTip);
- etKey = (EditText) findViewById(R.id.etKey);
- etStr = (EditText) findViewById(R.id.etStr);
- btnEncrypt = (Button) findViewById(R.id.btnEncrypt);
- btnEncrypt.setOnClickListener(this);
- btnDecrypt = (Button) findViewById(R.id.btnDecrypt);
- btnDecrypt.setOnClickListener(this);
- btnEncrypt.setEnabled(true);
- btnDecrypt.setEnabled(false);
- }
- @Override
- public void onClick(View v) {
- // TODO Auto-generated method stub
- if (v == btnEncrypt) {
- src = etStr.getText().toString().trim();
- key = etKey.getText().toString().trim();
- if (!src.equals("") && !key.equals("")) {
- try {
- dest = AESCipher.encrypt(key, src);
- tvTip.setText("Encrypted:");
- etStr.setText(dest);
- btnEncrypt.setEnabled(false);
- btnDecrypt.setEnabled(true);
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- } else if (v == btnDecrypt) {
- src = etStr.getText().toString().trim();
- key = etKey.getText().toString().trim();
- if (!src.equals("") && !key.equals("")) {
- try {
- dest = AESCipher.decrypt(key, src);
- tvTip.setText("Decrypted:");
- etStr.setText(dest);
- btnDecrypt.setEnabled(false);
- btnEncrypt.setEnabled(true);
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }else{
- tvTip.setText("Source:");
- btnDecrypt.setEnabled(false);
- btnEncrypt.setEnabled(true);
- }
- }
- }
- }
main.xml
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical" >
- <LinearLayout
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:orientation="vertical" >
- <TextView
- android:layout_width="100dp"
- android:layout_height="wrap_content"
- android:text="Key:" />
- <EditText
- android:id="@+id/etKey"
- android:layout_width="200dp"
- android:layout_height="40dp"
- android:maxLength="32"
- android:hint="Input the key" />
- </LinearLayout>
- <LinearLayout
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:orientation="vertical" >
- <TextView
- android:id="@+id/tvTip"
- android:layout_width="100dp"
- android:layout_height="wrap_content"
- android:text="Source:" />
- <EditText
- android:id="@+id/etStr"
- android:layout_width="400dp"
- android:layout_height="200dp"
- android:hint="Input the source"
- android:inputType="textMultiLine"
- android:maxLength="4096"
- android:maxLines="100"
- android:scrollHorizontally="false" />
- </LinearLayout>
- <LinearLayout
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:orientation="horizontal" >
- <Button
- android:id="@+id/btnEncrypt"
- android:layout_width="120dp"
- android:layout_height="50dp"
- android:text="加密字符串" />
- <Button
- android:id="@+id/btnDecrypt"
- android:layout_width="120dp"
- android:layout_height="50dp"
- android:text="解密字符串" />
- </LinearLayout>
- </LinearLayout>
AES加解密算法在Android中的应用及Android4.2以上版本调用问题的更多相关文章
- AES加解密算法Qt实现
[声明] (1) 本文源码 在一位未署名网友源码基础上,利用Qt编程,实现了AES加解密算法,并添加了文件加解密功能.在此表示感谢!该源码仅供学习交流,请勿用于商业目的. (2) 图片及描述 除图1外 ...
- AES加解密算法
直接粘代码,该类是基于微信公众号消息加密解密所提供的PHP DEMO改造而来,目前使用于彬彬大学APP接口token校验中. php的mcrypt 扩展已经过时了大约10年,并且用起来很复杂.因此它被 ...
- 最强加密算法?AES加解密算法Matlab和Verilog实现
目录 背景 AES加密的几种模式 基本运算 AES加密原理 Matlab实现 Verilog实现 Testbench 此本文首发于公众号[两猿社],重点讲述了AES加密算法的加密模式和原理,用MATL ...
- 【加解密专辑】对接触到的PGP、RSA、AES加解密算法整理
先贴代码,有空再整理思路 PGP加密 using System; using System.IO; using Org.BouncyCastle.Bcpg; using Org.BouncyCastl ...
- Aes 加解密算法
public class AesHelper { /// <summary> /// 生成128位的随机AES秘钥 /// </sum ...
- PHP完整的AES加解密算法使用及例子(256位)
依赖PHP自身的mcrypt扩展 <?php class aes { // CRYPTO_CIPHER_BLOCK_SIZE 32 private $_secret_key = 'default ...
- C#与java中的AES加解密互解算法
一.C#版AES加解密算法 public class AESCode { public string Key { get; set; } public string Encrypt(string va ...
- RSA,AES加解密算法的实现
目录 Python实现RSA公钥加密算法 RSA公钥加密算法原理 RSA算法的Python实现 AES加解密算法实现 AES加解密算法原理 AES加解密算法Python实现 参考文献 Python实现 ...
- Java中的AES加解密工具类:AESUtils
本人手写已测试,大家可以参考使用 package com.mirana.frame.utils.encrypt; import com.mirana.frame.constants.SysConsta ...
随机推荐
- PhpStorm,Pycharm,Goland破解
phpstorm是一个轻量级且便捷的PHP IDE,其旨在提供用户效率,可深刻理解用户的编码,提供智能代码补全,快速导航以及即时错误检查.不但是php开发的利器,前端开发也是毫不逊色的.下面记录Php ...
- 洛谷P1886 滑动窗口
传送门啦 以最大值为例,既然我们想要保证队列开头为答案,那么我们就要保证每次更新使最大值一直放在队列.那么如果存储的最大值该弹出了怎么办呢?我们只需要记录下每个元素的位置,判断是否在区间内即可. 队头 ...
- Angular2 CLI安装
官方文档: https://angular.cn/docs/ts/latest/cli-quickstart.html 实现步骤: 1.设置开发环境 2.创建新项目以及应用的骨架 3.启动开启服务 4 ...
- EntityFrameWork 图解
- K8S Dashborad登陆认证文档
K8S Dashboard是官方的一个基于WEB的用户界面,专门用来管理K8S集群,并可展示集群的状态.因为我们使用kubeadm搭建的集群会默认开启RABC(角色访问控制机制),所以我们必须要进行额 ...
- Java多线程及并发
进程:它是内存中的一段独立的空间. 线程:位于进程中,负责当前进程中的某个具备独立运行资格的空间. 进程是负责整个程序的运行,而线程是程序中具体的某个独立功能的运行.一个进程中至少应该有一个线程. 多 ...
- 009 jquery过滤选择器-----------(表单对象属性过滤选择器 与 表单选择器)
1.表单对象属性选择器 2.程序 <!DOCTYPE html> <html> <head> <meta charset="UTF-8"& ...
- 如何使用DSP的cache(转)
C6747在执行一块算法的执行时间在114ms左右,需求要20ms以下.6000属于分层存储器体系架构,内部RAM跟CPU不同频运行,只有cache使能才跟CPU同频.可能是cache没打开.下面转载 ...
- 【转】tair与redis比较总结
1. Tair总述 1.1 系统架构 一个Tair集群主要包括3个必选模块:configserver.dataserver和client,一个可选模块:invalidserver.通常情况下,一个集群 ...
- IdentityServer4系列之中文文档及实际项目经验分享
0.前言 原文:http://docs.identityserver.io/en/release/声明: 1.目录一至五章节根据IdentityServer英文文档翻译而来,有些内容会根据自己的理解来 ...