AES加密:

<span style="font-size:18px;">package com.example.encrypdate.util;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom; import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec; public class AES {
/**
* 加密
*
* @param content
* 须要加密的内容
* @param password
* 加密密码
* @return
*/
public static byte[] encrypt(String content, String password) {
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, new SecureRandom(password.getBytes()));
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");// 创建密码器
byte[] byteContent = content.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
byte[] result = cipher.doFinal(byteContent);
return result; // 加密
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
} /**
* 解密
*
* @param content
* 待解密内容
* @param password
* 解密密钥
* @return
*/
public static byte[] decrypt(byte[] content, String password) {
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, new SecureRandom(password.getBytes()));
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");// 创建密码器
cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
byte[] result = cipher.doFinal(content);
return result; // 加密
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
} /**
* 将十进制转换成16进制
*
* @param buf
* @return
*/
public static String parseByte2HexStr(byte buf[]) {
StringBuffer sb = new StringBuffer();
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;
} }</span>

DES加密:

<span style="font-size:18px;">package com.example.encrypdate.util;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec; import android.util.Base64; public class DES {
// 初始化向量,随机填充
private static byte[] iv = { 1, 2, 3, 4, 5, 6, 7, 8 }; /**
* @param encryptString
* 须要加密的明文
* @param encryptKey
* 秘钥
* @return 加密后的密文
* @throws Exception
*/
public static String encryptDES(String encryptString, String encryptKey)
throws Exception {
// 实例化IvParameterSpec对象,使用指定的初始化向量
IvParameterSpec zeroIv = new IvParameterSpec(iv);
// 实例化SecretKeySpec类,依据字节数组来构造SecretKey
SecretKeySpec key = new SecretKeySpec(encryptKey.getBytes(), "DES");
// 创建password器
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
// 用秘钥初始化Cipher对象
cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
// 运行加密操作
byte[] encryptedData = cipher.doFinal(encryptString.getBytes()); return Base64.encodeToString(encryptedData, Base64.DEFAULT);
} /****
*
* @param decrypString
* 密文
* @param decryptKey
* 解密密钥
* @return
* @throws Exception
*/
public static String decryptDES(String decrypString, String decryptKey)
throws Exception { byte[] byteMi = Base64.decode(decrypString, Base64.DEFAULT);
// 实例化IvParameterSpec对象,使用指定的初始化向量
IvParameterSpec zeroIv = new IvParameterSpec(iv);
// 实例化SecretKeySpec类。依据字节数组来构造SecretKey
SecretKeySpec key = new SecretKeySpec(decryptKey.getBytes(), "DES");
// 创建password器
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
// 用秘钥初始化Cipher对象
cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);
// 运行解密操作
byte[] decryptedData = cipher.doFinal(byteMi); return new String(decryptedData);
}
}</span>

MD5加密:

<span style="font-size:18px;">package com.example.encrypdate.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; public class MD5 { /***
* @param data
* @return
*/
public static String toMD5(String data) { try {
// 实例化一个指定摘要算法为MD5的MessageDigest对象
MessageDigest algorithm = MessageDigest.getInstance("MD5");
// 重置摘要以供再次使用
algorithm.reset();
// 使用bytes更新摘要
algorithm.update(data.getBytes());
// 使用指定的byte数组对摘要进行最的更新,然后完毕摘要计算
return toHexString(algorithm.digest(), "");
} catch (NoSuchAlgorithmException e) {
// TODO 自己主动生成的 catch 块
e.printStackTrace();
}
return "";
} // 将字符串中的每一个字符转换为十六进制
private static String toHexString(byte[] bytes, String separator) { StringBuilder hexstring = new StringBuilder();
for (byte b : bytes) {
String hex = Integer.toHexString(0xFF & b);
if (hex.length() == 1) {
hexstring.append('0');
}
hexstring.append(hex); } return hexstring.toString();
} }
</span>

測试文件:

<span style="font-size:18px;">package com.example.encrypdate;

import com.example.encrypdate.util.AES;
import com.example.encrypdate.util.DES; import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.widget.TextView;
import com.example.encrypdate.util.MD5; public class MainActivity extends Activity { private TextView tv; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) this.findViewById(R.id.tv);
// DESTest();
// MD5Test();
AESTest();
} public void DESTest() {
// 指定秘钥 仅仅能是8位
String key = "12345678";
// 指定须要加密的明文
String text = "多少";
Log.i("DES", "DES加密明文:" + text + "\n加密秘钥:" + key);
// 调用DES加密
try {
String encryptResult = DES.encryptDES(text, key);
String decryptResult = DES.decryptDES(encryptResult, key);
tv.setText("加密结果:" + encryptResult + "\n解密结果:" + decryptResult);
Log.i("DES", "加密结果:" + encryptResult + "\n解密结果:" + decryptResult);
} catch (Exception e) {
// TODO 自己主动生成的 catch 块
e.printStackTrace();
}
} private void AESTest() {
String content = "test3444";
String password = "11";
// 加密
byte[] encryptResult = AES.encrypt(content, password);
String encryptResultStr = AES.parseByte2HexStr(encryptResult);
// 解密
byte[] decryptFrom = AES.parseHexStr2Byte(encryptResultStr);
String decryptResult = new String(AES.decrypt(decryptFrom, password)); Log.i("AES", "密码:" + password + "\n加密前:" + content + "\n加密后:"
+ encryptResultStr + "\n解密后:" + decryptResult);
tv.setText("密码:" + password + "\n加密前:" + content + "\n加密后:"
+ encryptResultStr + "\n解密后:" + decryptResult);
} private void MD5Test() {
String str = "1nakjnvjanbdvjk女嘉宾那覅v骄傲不能浪费的哪里方便v啊别v骄傲不能浪费的哪里方便v啊别v骄傲不能浪费的哪里方便v啊别浪费vu巴娄病v阿拉伯风v ";
String MD5Result = MD5.toMD5(str);
Log.i("MD5", str + " MD5加密结果:" + MD5Result);
tv.setText(str + " MD5加密结果:" + MD5Result);
}
}
</span>

完整project地址:

http://download.csdn.net/detail/u014071669/7930951



另外,非对称加密RSA具体解释见:

http://blog.csdn.net/yongbingchao/article/details/39346099

版权声明:本文博客原创文章,博客,未经同意,不得转载。

Android DES AES MD5加密的更多相关文章

  1. Android数据加密之MD5加密

    前言: 项目中无论是密码的存储或者说判断文件是否是同一文件,都会用到MD5算法,今天来总结一下MD5加密算法. 什么是MD5加密? MD5英文全称“Message-Digest Algorithm 5 ...

  2. c# aes,des,md5加密等解密算法

    一:可逆加密,即是能加密也能解密 对称可逆加密:加密后能解密回原文,加密key和解密key是一个 加密算法都是公开的,密钥是保密的, 即使拿到密文 你是推算不了密钥 也推算不了原文 加密解密的速度快, ...

  3. IOS中DES与MD5加密方案

      0 2 项目中用的的加密算法,因为要和安卓版的适配,中间遇到许多麻烦. MD5算法和DES算法是常见的两种加密算法. MD5:MD5是一种不可逆的加密算法,按我的理解,所谓不可逆,就是不能解密,那 ...

  4. Vue AES+MD5加密 后台解密

    前端VUE vue项目中安装crypto-js npm install crypto-js --save-dev CryptoJS (crypto.js) 为 JavaScript 提供了各种各样的加 ...

  5. DES与MD5加密

    using System; using System.Data; using System.Configuration; using System.Web; using System.Security ...

  6. Android 手机卫士--md5加密过程

    在之前的文章中,我们将用户的密码使用SharedPreferences存储,我们打开/data/data/com.wuyudong.mobilesafe/shared_prefs文件夹下的 confi ...

  7. Android开发之MD5加密

    将字符串进行MD5加密,返回加密后的字符串 public static String encode(String password) { try { StringBuffer sb = new Str ...

  8. java, android的aes等加密库

    https://github.com/scottyab/AESCrypt-Android https://github.com/PDDStudio/EncryptedPreferences       ...

  9. Android数据加密之Rsa加密

    前言: 最近无意中和同事交流数据安全传输的问题,想起自己曾经使用过的Rsa非对称加密算法,闲下来总结一下. 其他几种加密方式: Android数据加密之Rsa加密 Android数据加密之Aes加密 ...

随机推荐

  1. iOS当该装置是水平屏,frame和bounds分别

    project那里有两个ViewControllers.间ViewController它是root view controller,红色背景,有一个顶button,点击加载后GreenViewCont ...

  2. 基于Qt有限状态机的一种实现方式和完善的人工智能方法

    基于Qt有限状态机的一种实现方式和完善的人工智能方法 人工智能在今年是一个非常火的方向,当然了.不不过今年,它一直火了非常多年,有关人工智能的一些算法层出不穷.人工智能在非常多领域都有应用,就拿我熟悉 ...

  3. ubuntu,从一个新用户,要转到新用户的命令行操作

    shibo-ubuntu@ubuntu:~$ sudo useradd karen [sudo] password for shibo-ubuntu:  shibo-ubuntu@ubuntu:~$ ...

  4. Atitit..文件上传组件选择and最佳实践的总结(2)----HTTP

    Atitit..文件上传组件选型and最佳实践总结(2)----断点续传 1. 断点续传的原理 1 2. 怎样推断一个插件/控件是否支持断点续传?? 1 3. 经常使用的组件选型结果::马 1 4.  ...

  5. Android使用代码消除App数据并重新启动设备

    /** * 使用代码消除App数据 * 我们不寻常的清除App数据,中找到相应的App * 然后选择其清除数据.以下给出代码实现. * * 注意事项: * 1 设备须要root * 2 该演示样例中删 ...

  6. Spring配置与第一Spring HelloWorld

    林炳文Evankaka原创作品. 转载请注明出处http://blog.csdn.net/evankaka 本文将主讲了Spring在Eclipse下的配置,并用Spring执行了第一个HelloWo ...

  7. java 正则表达式提取html纯文本

    本文来自我的个人博客: java 正则表达式提取html纯文本 做内容的大家都知道,从html中直接提取纯文本是一个非常大的问题.现将我做的正则匹配贴上: import java.util.regex ...

  8. HDU 4283 You are the one(间隔DP)

    标题效果: The TV shows such as You Are the One has been very popular. In order to meet the need of boys ...

  9. Android变化如何破解几场金

    我们在玩游戏的总会遇到一些东西需要购买,但是,我们可能要花钱,那么我们应该怎么办呢?这与游戏的插.我们在这里谈论的Android游戏,搜索互联网上的移动端游戏插件,您可能会发现一个叫段:八门神器.ap ...

  10. linux tar.gz zip 减压 压缩命令

    http://apps.hi.baidu.com/share/detail/37384818 download ADT link http://dl.google.com/android/ADT-0. ...