当前位置: 移动技术网 > 移动技术>移动开发>Android > android中AES加解密的使用方法

android中AES加解密的使用方法

2019年07月24日  | 移动技术网移动技术  | 我要评论

今天在android项目中使用aes对数据进行加解密,遇到了很多问题,网上也找了很多资料,也不行。不过最后还是让我给搞出来了,这里把这个记录下来,不要让别人走我的弯路,因为网上绝大多数的例子都是行不通的。好了,接下来开始讲解

1、aes工具类

package com.example.cheng.aesencrypt;

import android.text.textutils;

import java.security.nosuchalgorithmexception;
import java.security.securerandom;

import javax.crypto.cipher;
import javax.crypto.keygenerator;
import javax.crypto.secretkey;
import javax.crypto.spec.ivparameterspec;
import javax.crypto.spec.secretkeyspec;


/**
 * class description here
 *
 * @author cheng
 * @version 1.0.0
 * @since 2016-11-02
 */
public class aes {

 private static final string sha1prng = "sha1prng"; // sha1prng 强随机种子算法, 要区别4.2以上版本的调用方法
 private static final string iv = "qws871bz73msl9x8";
 private static final string aes = "aes"; //aes 加密
 private static final string ciphermode = "aes/cbc/pkcs5padding"; //algorithm/mode/padding

 /**
 * 加密
 */
 public static string encrypt(string key, string cleartext) {
 if (textutils.isempty(cleartext)) {
  return cleartext;
 }
 try {
  byte[] result = encrypt(key, cleartext.getbytes());
  return parsebyte2hexstr(result);
 } catch (exception e) {
  e.printstacktrace();
 }
 return null;
 }

 /**
 * 加密
 */
 public static byte[] encrypt(string key, byte[] clear) throws exception {
 byte[] raw = getrawkey(key.getbytes());
 secretkeyspec skeyspec = new secretkeyspec(raw, aes);
 cipher cipher = cipher.getinstance(ciphermode);
 cipher.init(cipher.encrypt_mode, skeyspec, new ivparameterspec(new byte[cipher.getblocksize()]));
 byte[] encrypted = cipher.dofinal(clear);
 return encrypted;
 }

 /**
 * 解密
 */
 public static string decrypt(string key, string encrypted) {
 if (textutils.isempty(encrypted)) {
  return encrypted;
 }
 try {
  byte[] enc = parsehexstr2byte(encrypted);
  byte[] result = decrypt(key, enc);
  return new string(result);
 } catch (exception e) {
  e.printstacktrace();
 }
 return null;
 }

 /**
 * 解密
 */
 public static byte[] decrypt(string key, byte[] encrypted) throws exception {
 byte[] raw = getrawkey(key.getbytes());
 secretkeyspec skeyspec = new secretkeyspec(raw, aes);
 cipher cipher = cipher.getinstance(ciphermode);
 cipher.init(cipher.decrypt_mode, skeyspec, new ivparameterspec(new byte[cipher.getblocksize()]));
 byte[] decrypted = cipher.dofinal(encrypted);
 return decrypted;
 }

 /**
 * 生成随机数,可以当做动态的密钥
 * 加密和解密的密钥必须一致,不然将不能解密
 */
 public static string generatekey() {
 try {
  securerandom securerandom = securerandom.getinstance(sha1prng);
  byte[] key = new byte[20];
  securerandom.nextbytes(key);
  return tohex(key);
 } catch (nosuchalgorithmexception e) {
  e.printstacktrace();
 }
 return null;
 }

 /**
 * 对密钥进行处理
 */
 public static byte[] getrawkey(byte[] seed) throws exception {
 keygenerator kgen = keygenerator.getinstance(aes);
 //for android
 securerandom sr = null;
 // 在4.2以上版本中,securerandom获取方式发生了改变
 if (android.os.build.version.sdk_int >= 17) {
  sr = securerandom.getinstance(sha1prng, "crypto");
 } else {
  sr = securerandom.getinstance(sha1prng);
 }
 // for java
 // securerandom = securerandom.getinstance(sha1prng);
 sr.setseed(seed);
 kgen.init(128, sr); //256 bits or 128 bits,192bits
 //aes中128位密钥版本有10个加密循环,192比特密钥版本有12个加密循环,256比特密钥版本则有14个加密循环。
 secretkey skey = kgen.generatekey();
 byte[] raw = skey.getencoded();
 return raw;
 }

 /**
 * 二进制转字符
 */
 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 static void appendhex(stringbuffer sb, byte b) {
 sb.append(iv.charat((b >> 4) & 0x0f)).append(iv.charat(b & 0x0f));
 }

 /**
 * 将二进制转换成16进制
 *
 * @param buf
 * @return
 */
 public static string parsebyte2hexstr(byte buf[]) {
 stringbuilder sb = new stringbuilder();
 for (int i = 0; i < buf.length; i++) {
  string hex = integer.tohexstring(buf[i] & 0xff);
  if (hex.length() == 1) {
  hex = '0' + hex;
  }
  sb.append(hex.touppercase());
 }
 return sb.tostring();
 }

 /**
 * 将16进制转换为二进制
 *
 * @param hexstr
 * @return
 */
 public static byte[] parsehexstr2byte(string hexstr) {
 if (hexstr.length() < 1)
  return null;
 byte[] result = new byte[hexstr.length() / 2];
 for (int i = 0; i < hexstr.length() / 2; i++) {
  int high = integer.parseint(hexstr.substring(i * 2, i * 2 + 1), 16);
  int low = integer.parseint(hexstr.substring(i * 2 + 1, i * 2 + 2),
   16);
  result[i] = (byte) (high * 16 + low);
 }
 return result;
 }
}

2、mainactivity和layout文件如下:

package com.example.cheng.aesencrypt;

import android.os.bundle;
import android.support.v7.app.appcompatactivity;
import android.view.view;
import android.widget.edittext;
import android.widget.textview;
import android.widget.toast;


public class mainactivity extends appcompatactivity {
 private edittext minputet;
 private textview mshowencryputtv;
 private textview mshowinputtv;
 private static final string password_string = "12345678";

 @override
 protected void oncreate(bundle savedinstancestate) {
 super.oncreate(savedinstancestate);
 setcontentview(r.layout.activity_main);
 minputet = (edittext) findviewbyid(r.id.ase_input);
 mshowencryputtv = (textview) findviewbyid(r.id.show_oringe_encrypt);
 mshowinputtv = (textview) findviewbyid(r.id.show_ase_encrypt);
 }

 /**
 * 加密
 *
 * @param view
 */
 public void encrypt(view view) {
 string inputstring = minputet.gettext().tostring().trim();
 if (inputstring.length() == 0) {
  toast.maketext(this, "请输入要加密的内容", toast.length_short).show();
  return;
 }
 string encrystr = aes.encrypt(password_string, inputstring);
 mshowinputtv.settext(encrystr);
 }

 /**
 * 解密
 *
 * @param view
 */
 public void decrypt(view view) {
 string encryptstring = mshowinputtv.gettext().tostring().trim();
 if (encryptstring.length() == 0) {
  toast.maketext(this, "解密字符串不能为空", toast.length_short).show();
  return;
 }
 string decrystr = aes.decrypt(password_string, encryptstring);
 mshowencryputtv.settext(decrystr);
 }
}

layout文件

<?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:id="@+id/activity_main"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:gravity="center_vertical"
 android:orientation="vertical"
 android:paddingbottom="@dimen/activity_vertical_margin"
 android:paddingleft="@dimen/activity_horizontal_margin"
 android:paddingright="@dimen/activity_horizontal_margin"
 android:paddingtop="@dimen/activity_vertical_margin"
 tools:context="com.example.cheng.aesencrypt.mainactivity">


 <edittext
 android:id="@+id/ase_input"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:hint="输入要加密的内容" />

 <button
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:onclick="encrypt"
 android:text="点击进行ase加密" />

 <textview
 android:id="@+id/show_ase_encrypt"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_margintop="10dp"
 android:text="显示加密后的内容" />

 <button
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:onclick="decrypt"
 android:text="点击进行ase解密" />

 <textview
 android:id="@+id/show_oringe_encrypt"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_margintop="10dp"
 android:text="显示加密后的内容" />

</linearlayout>

3、最后的效果如下:

1)、是一个输入框,输入钥加密的字符串;

2)、点击“aes加密”按钮后生产的加密字符串;

3)、点击“aes解密”按钮后,对加密字符串进行解密,然后在3处看到解密后的字符串,可以看到加密字符串和解密字符串相同,所以aes加解密成功了

4、总结

要用真机测试,模拟器是不行的,具体原因没去研究;
点击获取本例的github地址:
也可以通过android studio直接git下来,git地址为https://github.com/chenguo4930/androidaes.git
其中也还有des、rsa的加解密demo的github地址为https://github.com/chenguo4930/encodedemo
git地址为: https://github.com/chenguo4930/encodedemo.git

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网