1. AES加密,相对比较简单,之前已经配置好工具类。

package com.bbguoxue.poetry.util;
import java.security.SecureRandom; import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/**
* AES加密器
* @author Eric_Ni
*
*/
public class AESEncryptor { /**
* AES加密
*/
public static String encrypt(String seed, String cleartext) throws Exception {
byte[] rawKey = getRawKey(seed.getBytes());
byte[] result = encrypt(rawKey, cleartext.getBytes());
return toHex(result);
} /**
* AES解密
*/
public static String decrypt(String seed, String encrypted) throws Exception {
byte[] rawKey = getRawKey(seed.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");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG","Crypto");
sr.setSeed(seed);
kgen.init(128, sr); // 192 and 256 bits may not be available
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
return raw;
} private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(clear);
return encrypted;
} private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "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));
}
}

这里要注意的是红色行,在android4.X的时候可能出席问题。很多地方都是写SecureRandow.getInstance("SHA1PRNG")

2. 使用DES加密

//这个现在有点怕了,也还半知半解

private static final String DES_EDE     = "DESede/ECB/NoPadding";               //定义 加密算法,可用 DES,DESede,Blowfish        //keybyte为加密密钥,长度为24字节    //src为被加密的数据缓冲区(源)  
 
    private static final String DES_EDE_CBC = "DESede/CBC/NoPadding";               //定义 加密算法,可用 DES,DESede,Blowfish        //keybyte为加密密钥,长度为24字节    //src为被加密的数据缓冲区(源)  
 
    private static final String DES_CBC     = "DES/CBC/NoPadding";  
 
    private static final String DES_ECB     = "DES/ECB/PKCS5Padding";

// 还有"DES/CBC/PKCS5Padding"------------android常用

加密说明: 算法/工作模式/填充

主要涉及的几个问题:工作模式(如上:DES,DESede ...)、填充模式(PKCS5Padding, PKCS7Padding)、初始化向量(如下IvParameterSpec 这个东西容易出问题,注意很多地方初始化0000000,和12345678,这个东西只要有一位不同得到的结果肯定不同)

这几个变量如果你不指定的话,那么就要程序就要调用默认实现,java,android,iso。默认得到的结果肯定不同。

android可用模式,Ios去掉PKCS7Padding的方式得到的结果一样,能通用(Java中只能使用PKCS5Padding)

    private static String encrypt(byte[] raw, byte[] clear) throws Exception {
IvParameterSpec zeroIv = new IvParameterSpec(ivs);
SecretKeySpec skeySpec = new SecretKeySpec(raw, "DES");
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, zeroIv);
byte[] encrypted = cipher.doFinal(clear);
return toHex(encrypted);
}

//走的弯路

1. 类似AES那样生成密钥key。

2. 使用DESkey

        DESKeySpec dks = new DESKeySpec(raw);

        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
//key的长度不能够小于8位字节
Key secretKey = keyFactory.generateSecret(dks);
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec(new byte[8]);
AlgorithmParameterSpec paramSpec = iv;
cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec);
return cipher.doFinal(clear);

得到的结果总不对。可以和上面的比较一下,这个使用了DESKeySpec(这貌似用在ECB模式下),上面直接用的简单的SecretKeySpec。 本来也应该这样用的额,但互通性来说大家都简单的写了。

3. IvParameterSpec 这个类是很重要的, 这玩意是个初始化变量

很多地方可能使用示例new IvParamterSpec("12345678".getBytes()) ---------这其实在正常使用过程中常出现问题

很多都是用默认的{0,0,0,0,0,0,0,0}数组

我的整个代码

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec; /**
* AES加密器
*
* @author Eric_Ni
*
*/
public class AESEncryptor {
public static void main(String[] args) {
try {
System.out.println(encryptDES("123456", "dfardfsf"));
System.out.println(encrypt("dfardfsf", "123456"));
System.out.println(decrypt("dfardfsf", "B8CF276AF590D8B9"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} /**
* AES加密
*/
public static String encrypt(String seed, String cleartext)
throws Exception {
return encrypt(seed.getBytes(), cleartext.getBytes());
} /**
* AES解密
*/
public static String decrypt(String seed, String encrypted)
throws Exception {
byte[] enc = toByte(encrypted);
byte[] result = decrypt(seed, enc);
return new String(result);
} private static byte[] ivs = { 0, 0, 0, 0, 0, 0, 0, 0 }; public static String encryptDES(String encryptString, String encryptKey)
throws Exception {
IvParameterSpec zeroIv = new IvParameterSpec(new byte[8]);
SecretKeySpec key = new SecretKeySpec(encryptKey.getBytes(), "DES");
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
byte[] encryptedData = cipher.doFinal(encryptString.getBytes()); return toHex(encryptedData);
} private static String encrypt(byte[] raw, byte[] clear) throws Exception {
IvParameterSpec zeroIv = new IvParameterSpec(ivs);
SecretKeySpec skeySpec = new SecretKeySpec(raw, "DES");
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, zeroIv);
byte[] encrypted = cipher.doFinal(clear);
return toHex(encrypted);
} private static byte[] decrypt(String raw, byte[] encrypted)
throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw.getBytes(), "DES");
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec(ivs);
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
return cipher.doFinal(encrypted);
} public static String toHex(String txt) {
return toHex(txt.getBytes());
} public static String fromHex(String hex) {
return new String(hex.getBytes());
} 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));
}
}

JAVA中基本就只用这种了,如果需要使用其他的可以参考如下文章,未测试。

最后分享一下一位兄弟的总结,太多了没想去详细看

主要搞android,太复杂了还是用c做比较好点。不然容易被反编译

1.Base64
加密:org.apache.commons.codec.binary.Base64.encodeBase64(byte[] binaryData)
解密:org.apache.commons.codec.binary.Base64.decodeBase64(byte[] base64Data)
2.Md5
加密:org.apache.commons.codec.digest.md5Hex(byte[] data)
解密:无
3.DES(des-ecb,3des,des-cbc,cbc-mac)
view plaincopy to clipboardprint?
import java.io.ByteArrayOutputStream;
import java.security.SecureRandom;
import java.util.Arrays; import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec; import org.bouncycastle.crypto.BlockCipher;
import org.bouncycastle.crypto.Mac;
import org.bouncycastle.crypto.engines.DESEngine;
import org.bouncycastle.crypto.macs.CBCBlockCipherMac;
import org.bouncycastle.crypto.params.KeyParameter; import com.alibaba.common.lang.StringUtil;
import com.huateng.commons.lang.convert.HexUtils; public class ShfftDes {
//验证用密钥
private byte[] key = "000000000000000000000000".getBytes(); // private byte[] key = Hex.decode("00000000"); private byte[] ivs = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }; private static final String DES_EDE = "DESede/ECB/NoPadding"; //定义 加密算法,可用 DES,DESede,Blowfish //keybyte为加密密钥,长度为24字节 //src为被加密的数据缓冲区(源) private static final String DES_EDE_CBC = "DESede/CBC/NoPadding"; //定义 加密算法,可用 DES,DESede,Blowfish //keybyte为加密密钥,长度为24字节 //src为被加密的数据缓冲区(源) private static final String DES_CBC = "DES/CBC/NoPadding"; private static final String DES_ECB = "DES/ECB/PKCS5Padding"; public byte[] CryptByDes(byte[] content, int mode) throws Exception {
Cipher cipher = Cipher.getInstance(DES_ECB);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(new DESKeySpec(key));
cipher.init(mode, secretKey);
return cipher.doFinal(content);
} public byte[] CryptBy3Des(byte[] content, int mode) throws Exception {
Cipher cipher = Cipher.getInstance(DES_EDE);
SecretKey secretKey = new SecretKeySpec(key, "DESede");
cipher.init(mode, secretKey);
return cipher.doFinal(content);
} public byte[] CryptByDesCbc(byte[] content, int mode) throws Exception {
Cipher cipher = Cipher.getInstance(DES_CBC);
SecretKey secureKey = new SecretKeySpec(key, "DES");
IvParameterSpec iv = new IvParameterSpec(ivs);
cipher.init(mode, secureKey, iv);
return cipher.doFinal(HexUtils.fromHex(new String(content)));
} public byte[] CryptBy3DesCbc(byte[] content, int mode) throws Exception {
Cipher cipher = Cipher.getInstance(DES_EDE_CBC);
SecretKey secureKey = new SecretKeySpec(key, "DESede");
IvParameterSpec iv = new IvParameterSpec(ivs);
cipher.init(mode, secureKey, iv);
return cipher.doFinal(content);
} public byte[] CryptByDesCbcMac(byte[] content) throws Exception {
BlockCipher engine = new DESEngine();
Mac mac = new CBCBlockCipherMac(engine, 64);
byte[] macText = new byte[engine.getBlockSize()];
mac.init(new KeyParameter(key));
mac.update(Padding(content, 64), 0, content.length);
mac.update(content, 0, content.length);
mac.doFinal(macText, 0);
return macText;
} public byte[] ShFftCryptByDessdsCbc(byte[] content, int mode) throws Exception {
byte[] ks1 = HexUtils.fromHex(new String(key));
byte[] ks = new byte[24];
System.arraycopy(ks1, 0, ks, 0, ks1.length);
System.arraycopy(ks1, 0, ks, ks1.length, 8); Cipher cipher = Cipher.getInstance(DES_EDE_CBC);
SecretKeyFactory keyFactory = null;
keyFactory = SecretKeyFactory.getInstance("DESede");
SecretKey secretKey = null;
secretKey = keyFactory.generateSecret(new DESedeKeySpec(ks));
IvParameterSpec iv = new IvParameterSpec(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 });
cipher.init(mode, secretKey, iv);
return cipher.doFinal(HexUtils.fromHex(new String(content)));
} public byte[] mac(byte[] content) throws Exception {
int len;
byte plainData[];
byte encryptedData[];
len = (content.length / 8 + (content.length % 8 != 0 ? 1 : 0)) * 8;
plainData = new byte[len];
encryptedData = new byte[8];
Arrays.fill(plainData, (byte) 32);
System.arraycopy(content, 0, plainData, 0, content.length);
SecureRandom sr = new SecureRandom();
DESKeySpec dks = new DESKeySpec(key);
SecretKeyFactory keyFactory = null;
keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(dks);
Cipher cipher = Cipher.getInstance("DES/CBC/NoPadding");
IvParameterSpec iv = new IvParameterSpec(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 });
cipher.init(1, secretKey, iv, sr);
System.arraycopy(cipher.doFinal(plainData), len - 8, encryptedData, 0, 8);
return encryptedData;
} public byte[] Padding(byte[] content, int block) {
int contentLength = content.length;
int mod = contentLength % block;
if (mod != 0) {
int size = contentLength + block - mod;
// String s = new String(content);
// StringUtil.alignLeft(s, size, " ");
byte[] s = new byte[size];
System.arraycopy(content, 0, s, 0, content.length);
for (int i = content.length; i < size; i++) {
s[i] = 32;
}
return s;
}
return content;
} public String Padding(String content, int block) {
int contentLength = content.length();
int mod = contentLength % block;
if (mod != 0) {
int size = contentLength + block - mod;
String s = new String(content);
StringUtil.alignLeft(s, size, " ");
return s;
}
return content;
} public void println(byte[] bs) {
for (byte b : bs) {
System.out.print(b + " ");
}
System.out.println();
} public void printlnByte(byte[] bs) {
for (byte b : bs) {
if (b < 0) {
System.out.print((int) b + 256 + " ");
} else {
System.out.print(b + " ");
}
}
System.out.println();
} public void printlnByteInt16(byte[] bs) {
for (byte b : bs) {
System.out.print(Integer.toHexString((int) b) + " ");
}
System.out.println();
} public String dumpBytes(byte[] bytes) {
int i;
StringBuffer sb = new StringBuffer();
for (i = 0; i < bytes.length; i++) {
int n = bytes[i] >= 0 ? bytes[i] : 256 + bytes[i];
String s = Integer.toHexString(n);
if (s.length() < 2) {
s = "0" + s;
}
if (s.length() > 2) {
s = s.substring(s.length() - 2);
}
sb.append(s);
}
return sb.toString().toUpperCase();
//return new BASE64Encoder().encode(bytes);
} // 一下程序将每2位16进制整数组装成一个字节
private String hexString = "0123456789ABCDEF"; public byte[] decode(String bytes) {
ByteArrayOutputStream baos = new ByteArrayOutputStream(bytes.length() / 2);
for (int i = 0; i < bytes.length(); i += 2)
baos.write((hexString.indexOf(bytes.charAt(i)) << 4 | hexString.indexOf(bytes
.charAt(i + 1))));
return baos.toByteArray();
} public byte[] getKey() {
return key;
} public void setKey(byte[] key) {
this.key = key;
} public byte[] getIvs() {
return ivs;
} public void setIvs(byte[] ivs) {
this.ivs = ivs;
} }

浅谈DEs,AES的更多相关文章

  1. 浅谈DES加密算法

    一.DES加密算法介绍 1.要求密钥必须是8个字节,即64bit长度 2.因为密钥是byte[8] , 代表字符串也可以是非可见的字节,可以与Base64编码算法一起使用 3.加密.解密都需要通过字节 ...

  2. 浅谈RSA加密算法

    一.什么是非对称加密 1.加密的密钥与加密的密钥不相同,这样的加密算法称之为非对称加密 2.密钥分为:公钥,私钥  公钥:可以对外给任何人的加密和解密的密码,是公开的 私钥:通过私钥可以生成公钥,但从 ...

  3. Android安全开发之浅谈密钥硬编码

    Android安全开发之浅谈密钥硬编码 作者:伊樵.呆狐@阿里聚安全 1 简介 在阿里聚安全的漏洞扫描器中和人工APP安全审计中,经常发现有开发者将密钥硬编码在Java代码.文件中,这样做会引起很大风 ...

  4. Android应用安全开发之浅谈加密算法的坑

      <Android应用安全开发之浅谈加密算法的坑> 作者:阿里移动安全@伊樵,@舟海 阿里聚安全,一站式解决应用开发安全问题     Android开发中,难免会遇到需要加解密一些数据内 ...

  5. 【推荐】JAVA基础◆浅谈3DES加密解密

    国内私募机构九鼎控股打造APP,来就送 20元现金领取地址:http://jdb.jiudingcapital.com/phone.html内部邀请码:C8E245J (不写邀请码,没有现金送)国内私 ...

  6. Atitit.加密算法 des  aes 各个语言不同的原理与解决方案java php c#

    Atitit.加密算法 des  aes 各个语言不同的原理与解决方案java php c# 1. 加密算法的参数::算法/模式/填充 1 2. 标准加密api使用流程1 2.1. Md5——16bi ...

  7. 浅谈HTTPS以及Fiddler抓取HTTPS协议

    最近想尝试基于Fiddler的录制功能做一些接口的获取和处理工作,碰到的一个问题就是简单连接Fiddler只能抓取HTTP协议,关键的登录请求等HTTPS协议都没有捕捉到,所以想让Fiddler能够同 ...

  8. [转]浅谈https\ssl\数字证书

    浅谈https\ssl\数字证书 http://www.cnblogs.com/P_Chou/archive/2010/12/27/https-ssl-certification.html 全球可信的 ...

  9. 浅谈HTTPS以及Fiddler抓取HTTPS协议(摘抄)

    一.浅谈HTTPS 我们都知道HTTP并非是安全传输,在HTTPS基础上使用SSL协议进行加密构成的HTTPS协议是相对安全的.目前越来越多的企业选择使用HTTPS协议与用户进行通信,如百度.谷歌等. ...

随机推荐

  1. ASP.NET MVC开发微信(一)

    public string index() { return Content(""); }

  2. 创建一个提供数据 API 的 Node.js 网站

    创建站点目录 首先,创建一个文件夹用来保存你的站点文件,使用 mkdir 就可以了 PS C:\> mkdir mysite 然后,进入到这个文件夹进行下一步的操作. 创建包说明 使用记事本或者 ...

  3. 使用postman玩转接口测试

    (一)前言: 之前搞自动化接口测试,由于接口的特性,要验证接口返回xml中的数据,所以没找到合适的轮子,就自己用requests造了个轮子,用着也还行,不过就是case管理有些麻烦,近几天又回头看了看 ...

  4. Yii 中比较常用的rules验证规则记录

    查看代码   打印 01 return array( 02   03     //必须填写 04     array('email, username, password,agree,verifyPa ...

  5. sqlserver 常用sql语句

    SELECT COUNT(*) FROM WeixinUser SELECT COUNT(*) FROM WeixinUser WHERE datediff(day, CreateTime,getda ...

  6. 把数组转换成sql中能使用的字符串

    1.数组对象转换成字符串,拼接成符合sql语句的语法 2.代码如下例子 public static void testString(){        String[] str=new String[ ...

  7. javascript代码复用模式(二)

    前面说到,javascript的代码复用模式,可分为类式继承和非类式继承(现代继承).这篇就继续类式继承. 类式继承模式-借用构造函数 使用借用构造函数的方法,可以从子构造函数得到父构造函数传任意数量 ...

  8. jQuery之Nestable

    空间属性置顶: 属性 说明 change 事件,当控件改变时触发 nestable 方法,获取顺序JSON数据,形式如下: [{"id":1},{"id":2} ...

  9. c#实现每隔规定时间自动执行程序代码

    c#实现每隔规定时间自动执行程序代码  在一般的项目中我们很少用到c#实现每隔规定时间自动执行程序代码,但是如果你经历的项目多,或者应用程序做的比较多的话,c#实现每隔规定时间自动执行程序代码就用的比 ...

  10. 【linux】Ubuntu 14.04 smba服务器的配置

    SMB(Server Messages Block,信息服务块)是为了在ubuntu虚拟机与windows之间共享文件. 具体配置过程如下:   (1)安装SMB应用 sudo  apt-get in ...