最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

android中AES加解密的使用方法

 更新時(shí)間:2016年11月03日 08:38:32   作者:柒號(hào)公園  
這篇文章主要為大家詳細(xì)介紹了android中AES加解密的使用方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

今天在android項(xiàng)目中使用AES對(duì)數(shù)據(jù)進(jìn)行加解密,遇到了很多問(wèn)題,網(wǎng)上也找了很多資料,也不行。不過(guò)最后還是讓我給搞出來(lái)了,這里把這個(gè)記錄下來(lái),不要讓別人走我的彎路,因?yàn)榫W(wǎng)上絕大多數(shù)的例子都是行不通的。好了,接下來(lái)開(kāi)始講解

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 強(qiáng)隨機(jī)種子算法, 要區(qū)別4.2以上版本的調(diào)用方法
 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;
 }

 /**
 * 生成隨機(jī)數(shù),可以當(dāng)做動(dòng)態(tài)的密鑰
 * 加密和解密的密鑰必須一致,不然將不能解密
 */
 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;
 }

 /**
 * 對(duì)密鑰進(jìn)行處理
 */
 public static byte[] getRawKey(byte[] seed) throws Exception {
 KeyGenerator kgen = KeyGenerator.getInstance(AES);
 //for android
 SecureRandom sr = null;
 // 在4.2以上版本中,SecureRandom獲取方式發(fā)生了改變
 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個(gè)加密循環(huán),192比特密鑰版本有12個(gè)加密循環(huán),256比特密鑰版本則有14個(gè)加密循環(huán)。
 SecretKey skey = kgen.generateKey();
 byte[] raw = skey.getEncoded();
 return raw;
 }

 /**
 * 二進(jìn)制轉(zhuǎn)字符
 */
 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));
 }

 /**
 * 將二進(jìn)制轉(zhuǎn)換成16進(jìn)制
 *
 * @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進(jìn)制轉(zhuǎn)換為二進(jìn)制
 *
 * @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, "請(qǐng)輸入要加密的內(nèi)容", 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="輸入要加密的內(nèi)容" />

 <Button
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:onClick="encrypt"
 android:text="點(diǎn)擊進(jìn)行ASE加密" />

 <TextView
 android:id="@+id/show_ase_encrypt"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_marginTop="10dp"
 android:text="顯示加密后的內(nèi)容" />

 <Button
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:onClick="decrypt"
 android:text="點(diǎn)擊進(jìn)行ASE解密" />

 <TextView
 android:id="@+id/show_oringe_encrypt"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_marginTop="10dp"
 android:text="顯示加密后的內(nèi)容" />

</LinearLayout>

3、最后的效果如下:

1)、是一個(gè)輸入框,輸入鑰加密的字符串;

2)、點(diǎn)擊“AES加密”按鈕后生產(chǎn)的加密字符串;

3)、點(diǎn)擊“AES解密”按鈕后,對(duì)加密字符串進(jìn)行解密,然后在3處看到解密后的字符串,可以看到加密字符串和解密字符串相同,所以AES加解密成功了

4、總結(jié)

要用真機(jī)測(cè)試,模擬器是不行的,具體原因沒(méi)去研究;
點(diǎn)擊獲取本例的github地址:
也可以通過(guò)android studio直接git下來(lái),git地址為https://github.com/chenguo4930/AndroidAES.git
其中也還有DES、RSA的加解密demo的github地址為https://github.com/chenguo4930/EncodeDemo
git地址為: https://github.com/chenguo4930/EncodeDemo.git

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Android ListView和Adapter數(shù)據(jù)適配器的簡(jiǎn)單介紹

    Android ListView和Adapter數(shù)據(jù)適配器的簡(jiǎn)單介紹

    這篇文章主要介紹了Android ListView和Adapter數(shù)據(jù)適配器的簡(jiǎn)單介紹,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2018-04-04
  • 一文講解Kotlin中的contract到底有什么用

    一文講解Kotlin中的contract到底有什么用

    我們?cè)陂_(kāi)發(fā)中肯定會(huì)經(jīng)常用Kotlin提供的一些通用拓展函數(shù),當(dāng)我們進(jìn)去看源碼的時(shí)候會(huì)發(fā)現(xiàn)許多函數(shù)里面有contract{}包裹的代碼塊,那么這些代碼塊到底有什么作用呢?下面這篇文章主要給大家介紹了關(guān)于Kotlin中contract到底有什么用的相關(guān)資料,需要的朋友可以參考下
    2022-01-01
  • Android App中使用ListFragment的實(shí)例教程

    Android App中使用ListFragment的實(shí)例教程

    這篇文章主要介紹了Android App中使用ListFragment的實(shí)例教程,ListFragment的內(nèi)容是以列表(list)的形式顯示的Fragment,需要的朋友可以參考下
    2016-05-05
  • Android開(kāi)發(fā)Retrofit源碼分析

    Android開(kāi)發(fā)Retrofit源碼分析

    這篇文章主要為大家介紹了Android開(kāi)發(fā)Retrofit源碼分析詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-07-07
  • Android五子棋游戲程序完整實(shí)例分析

    Android五子棋游戲程序完整實(shí)例分析

    這篇文章主要為大家分享了Android五子棋游戲程序完整實(shí)例,內(nèi)容豐富,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2016-04-04
  • Android?Adapter適配器使用示例講解

    Android?Adapter適配器使用示例講解

    這篇文章主要為大家介紹了Android?Adapter適配器使用示例講解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-04-04
  • Android的分辨率和屏幕適配詳解

    Android的分辨率和屏幕適配詳解

    對(duì)于剛接觸Android的新人和剛走上Android技術(shù)崗位的開(kāi)發(fā)者們來(lái)說(shuō),在熟悉了相關(guān)之后,在項(xiàng)目完成后,就會(huì)面臨著一個(gè)重大的挑戰(zhàn),那么就是屏幕適配的問(wèn)題。當(dāng)然我們所說(shuō)的屏幕適配指的是適配各種手機(jī)不同的分辨率。
    2016-09-09
  • Android Studio實(shí)現(xiàn)發(fā)短信功能

    Android Studio實(shí)現(xiàn)發(fā)短信功能

    這篇文章主要介紹了Android Studio實(shí)現(xiàn)發(fā)短信功能,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下
    2017-06-06
  • Android中發(fā)送Http請(qǐng)求(包括文件上傳、servlet接收)的實(shí)例代碼

    Android中發(fā)送Http請(qǐng)求(包括文件上傳、servlet接收)的實(shí)例代碼

    首先我是寫了個(gè)java工程測(cè)試發(fā)送post請(qǐng)求:可以包含文本參數(shù)和文件參數(shù)
    2013-05-05
  • Android高性能日志寫入方案的實(shí)現(xiàn)

    Android高性能日志寫入方案的實(shí)現(xiàn)

    這篇文章主要給大家介紹了關(guān)于Android高性能日志寫入方案的實(shí)現(xiàn)方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-01-01

最新評(píng)論

张家口市| 安吉县| 田东县| 北辰区| 岳池县| 兖州市| 武邑县| 阜阳市| 丰原市| 连南| 和平区| 祁东县| 湘潭县| 荣昌县| 天峻县| 临沂市| 白山市| 外汇| 互助| 灵台县| 江都市| 梨树县| 壶关县| 永靖县| 耒阳市| 山阴县| 乐昌市| 长兴县| 腾冲县| 铜山县| 慈利县| 昌江| 中牟县| 谢通门县| 石门县| 宜兰县| 涿鹿县| 巩义市| 梅州市| 浠水县| 阜新|