AES - 高级加密标准:

  高级加密标准(英语:Advanced Encryption Standard,缩写:AES),在密码学中又称Rijndael加密法,是美国联邦政府采用的一种区块加密标准。这个标准用来替代原先的DES,已经被多方分析且广为全世界所使用。经过五年的甄选流程,高级加密标准由美国国家标准与技术研究院(NIST)于2001年11月26日发布于FIPS PUB 197,并在2002年5月26日成为有效的标准。2006年,高级加密标准已然成为对称密钥加密中最流行的算法之一

AES 算法在工作中使用很频繁, 借着这次项目中使用做一下总结, 本次主要是正对 AES512 来讲解。

开发前准备工作:

由于Java 运行环境中的 policy文件是受限的,对AES512不支持。解决方案如下:

  1:policy文件位于${java_home}/jre/lib/security目录下

  2: 去除该限制需下载 JavaCryptography Extension (JCE) Unlimited Strength JurisdictionPolicy Files,
    覆盖上述目录下的对应jar文件(local_policy.jar,US_export_policy.jar)

  3: jar 官方下载路径

    JDK6 http://www.oracle.com/technetwork/java/javase/downloads/jce-6-download-429243.html

    JDK7 http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html
    JDK8 http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html

做完这三步 下面直接上代码:

AES512 加密方法

 import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException; import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec; import org.message.encrypt.tool.Encode;
import org.message.encrypt.tool.Numeric; import com.google.common.io.BaseEncoding; public class AESCipher {
private static final String ALGORITHM_AES256 = "AES/CBC/PKCS5Padding";// "AES/CBC/PKCS7Padding";
private final SecretKeySpec secretKeySpec;
private static final String CHARSET = "UTF-8";
private static final String DEFAULT_IV = "iv is default value";
private Cipher cipher;
private IvParameterSpec iv; public AESCipher(String key) {
this(key, DEFAULT_IV);
} public AESCipher(String key, String iv) {
this(Numeric.hexStringToByteArray(key), Numeric.hexStringToByteArray(iv));
} private AESCipher(byte[] key, byte[] iv) {
// Security.addProvider(new BouncyCastleProvider());
if (null == key || key.length != 32) {
throw new RuntimeException("input params key must be 32bit bytes array");
}
if (null == iv || iv.length != 16) {
throw new RuntimeException("input params iv must be 16bit bytes array");
}
this.secretKeySpec = new SecretKeySpec(key, "AES");
this.iv = new IvParameterSpec(iv);
try {
this.cipher = Cipher.getInstance(ALGORITHM_AES256);
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
throw new RuntimeException("instantiation objects Cipher exception");
}
} /**
* AES Encrypt algorithm
*
* @param encryptSource
* not null string
* @return after AES encrypt result , the type of the string
*/
public String getEncryptedMessage(final String encryptSource) {
Cipher cipher = getCipher(Cipher.ENCRYPT_MODE);
byte[] encryptedTextBytes = null;
try {
encryptedTextBytes = cipher.doFinal(encryptSource.getBytes(CHARSET));
} catch (IllegalBlockSizeException | BadPaddingException | UnsupportedEncodingException e) {
throw new RuntimeException("AES encrypt exception");
}
return Encode.baseEncode(encryptedTextBytes);
} /**
* AES decrypt algorithm
*
* @param decryptSource
* AES encrypted cipher, type of String
* @return decrypted plaintext, type of string
*/
public String getDecryptMessage(String decryptSource) { Cipher cipher = getCipher(Cipher.DECRYPT_MODE);
byte[] encryptedTextBytes = null;
String decryptResult = null;
try {
encryptedTextBytes = cipher.doFinal(BaseEncoding.base64().decode(decryptSource));
} catch (IllegalBlockSizeException | BadPaddingException e) {
throw new RuntimeException("AES decrypt exception");
}
try {
decryptResult = new String(encryptedTextBytes, CHARSET);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("bytes array convert into string exception");
}
return decryptResult;
} private Cipher getCipher(int encryptMode) {
try {
cipher.init(encryptMode, secretKeySpec, iv);
} catch (InvalidKeyException | InvalidAlgorithmParameterException e) {
throw new RuntimeException("init objects Cipher exception");
}
return cipher;
}
}

Encode 工具类

 import com.google.common.io.BaseEncoding;

 public class Encode {

     /**
* byte[] convert into string ,use base encode default value BASE64
*
* @param encodeMassage
* not null byte[]
* @return after encode result
*/
public static String baseEncode(final byte[] encodeMassage) {
return baseEncode(encodeMassage, BaseType.BASE64);
} /**
* byte[] convert into string ,use base encode default value BASE64
*
* @param encodeMassage
* not null byte[]
* @param encoder
* of type please see enum type of inner class , the class name
* 'BaseType'
* @return after encode result , the type of string
*/
public static String baseEncode(final byte[] encodeMassage, final BaseType encoder) {
String baseResult = null;
switch (encoder) {
case BASE64:
baseResult = BaseEncoding.base64().encode(encodeMassage);
break;
case BASE32:
baseResult = BaseEncoding.base32().encode(encodeMassage);
break;
case BASE32HEX:
baseResult = BaseEncoding.base32Hex().encode(encodeMassage);
break;
case BASE16:
baseResult = BaseEncoding.base16().encode(encodeMassage);
break;
default:
break;
}
return baseResult;
} /**
* string convert into byte[], use base decode
*
* @param decodeMassage
* not null string
* @return after decode result , the type of byte[]
*/
public static byte[] baseDecode(final String decodeMassage) {
return baseDecode(decodeMassage, BaseType.BASE64);
} public static byte[] baseDecode(final String decodeMassage, final BaseType encoder) {
byte[] baseResult = null;
switch (encoder) {
case BASE64:
baseResult = BaseEncoding.base64().decode(decodeMassage);
break;
case BASE32:
baseResult = BaseEncoding.base32().decode(decodeMassage);
break;
case BASE32HEX:
baseResult = BaseEncoding.base32Hex().decode(decodeMassage);
break;
case BASE16:
baseResult = BaseEncoding.base16().decode(decodeMassage);
break;
default:
break;
}
return baseResult;
} enum BaseType {
BASE64, BASE32, BASE32HEX, BASE16;
}
}

Numeric 工具类

 import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Arrays; /**
* <p>Message codec functions.</p>
*
* <p>Implementation as per https://github.com/ethereum/wiki/wiki/JSON-RPC#hex-value-encoding</p>
*/
public final class Numeric { private static final String HEX_PREFIX = "0x"; private Numeric() {
} public static String encodeQuantity(BigInteger value) {
if (value.signum() != -1) {
return HEX_PREFIX + value.toString(16);
} else {
throw new RuntimeException("Negative values are not supported");
}
} public static BigInteger decodeQuantity(String value) {
if (!isValidHexQuantity(value)) {
throw new RuntimeException("Value must be in format 0x[1-9]+[0-9]* or 0x0");
}
try {
return new BigInteger(value.substring(2), 16);
} catch (NumberFormatException e) {
throw new RuntimeException("Negative ", e);
}
} private static boolean isValidHexQuantity(String value) {
if (value == null) {
return false;
} if (value.length() < 3) {
return false;
} if (!value.startsWith(HEX_PREFIX)) {
return false;
} // If TestRpc resolves the following issue, we can reinstate this code
// https://github.com/ethereumjs/testrpc/issues/220
// if (value.length() > 3 && value.charAt(2) == '0') {
// return false;
// } return true;
} public static String cleanHexPrefix(String input) {
if (containsHexPrefix(input)) {
return input.substring(2);
} else {
return input;
}
} public static String prependHexPrefix(String input) {
if (!containsHexPrefix(input)) {
return HEX_PREFIX + input;
} else {
return input;
}
} public static boolean containsHexPrefix(String input) {
return input.length() > 1 && input.charAt(0) == '0' && input.charAt(1) == 'x';
} public static BigInteger toBigInt(byte[] value, int offset, int length) {
return toBigInt((Arrays.copyOfRange(value, offset, offset + length)));
} public static BigInteger toBigInt(byte[] value) {
return new BigInteger(1, value);
} public static BigInteger toBigInt(String hexValue) {
String cleanValue = cleanHexPrefix(hexValue);
return new BigInteger(cleanValue, 16);
} public static String toHexStringWithPrefix(BigInteger value) {
return HEX_PREFIX + value.toString(16);
} public static String toHexStringNoPrefix(BigInteger value) {
return value.toString(16);
} public static String toHexStringWithPrefixZeroPadded(BigInteger value, int size) {
return toHexStringZeroPadded(value, size, true);
} public static String toHexStringNoPrefixZeroPadded(BigInteger value, int size) {
return toHexStringZeroPadded(value, size, false);
} private static String toHexStringZeroPadded(BigInteger value, int size, boolean withPrefix) {
String result = toHexStringNoPrefix(value); int length = result.length();
if (length > size) {
throw new UnsupportedOperationException(
"Value " + result + "is larger then length " + size);
} else if (value.signum() < 0) {
throw new UnsupportedOperationException("Value cannot be negative");
} if (length < size) {
result = Strings.zeros(size - length) + result;
} if (withPrefix) {
return HEX_PREFIX + result;
} else {
return result;
}
} public static byte[] toBytesPadded(BigInteger value, int length) {
byte[] result = new byte[length];
byte[] bytes = value.toByteArray(); int bytesLength;
int srcOffset;
if (bytes[0] == 0) {
bytesLength = bytes.length - 1;
srcOffset = 1;
} else {
bytesLength = bytes.length;
srcOffset = 0;
} if (bytesLength > length) {
throw new RuntimeException("Input is too large to put in byte array of size " + length);
} int destOffset = length - bytesLength;
System.arraycopy(bytes, srcOffset, result, destOffset, bytesLength);
return result;
} public static byte[] hexStringToByteArray(String input) {
String cleanInput = cleanHexPrefix(input); int len = cleanInput.length(); if (len == 0) {
return new byte[] {};
} byte[] data;
int startIdx;
if (len % 2 != 0) {
data = new byte[(len / 2) + 1];
data[0] = (byte) Character.digit(cleanInput.charAt(0), 16);
startIdx = 1;
} else {
data = new byte[len / 2];
startIdx = 0;
} for (int i = startIdx; i < len; i += 2) {
data[(i + 1) / 2] = (byte) ((Character.digit(cleanInput.charAt(i), 16) << 4)
+ Character.digit(cleanInput.charAt(i+1), 16));
}
return data;
} public static String toHexString(byte[] input, int offset, int length, boolean withPrefix) {
StringBuilder stringBuilder = new StringBuilder();
if (withPrefix) {
stringBuilder.append("0x");
}
for (int i = offset; i < offset + length; i++) {
stringBuilder.append(String.format("%02x", input[i] & 0xFF));
} return stringBuilder.toString();
} public static String toHexStringNoPrefix(byte[] input) {
return toHexString(input, 0, input.length, false);
} public static String toHexString(byte[] input) {
return toHexString(input, 0, input.length, true);
} public static byte b(int m, int n) {
return (byte) ( (m << 4) | n);
} public static boolean isIntegerValue(BigDecimal value) {
return value.signum() == 0 ||
value.scale() <= 0 ||
value.stripTrailingZeros().scale() <= 0;
}
}

好了 这样 AES512 就实现了, 测试方法我在这就写了, 自己可以写个test 测试下。

Java AES512加密算法的更多相关文章

  1. java HMAC_SHA1加密算法

      java HMAC_SHA1加密算法 CreationTime--2018年7月14日16点46分 Author:Marydon 1.准备工作 import javax.crypto.Mac; i ...

  2. java sm3加密算法

      java sm3加密算法实现 CreationTime--2018年7月13日09点28分 Author:Marydon 1.准备工作 所需jar包: bcprov-jdk15on-1.59.ja ...

  3. java单向加密算法小结(2)--MD5哈希算法

    上一篇文章整理了Base64算法的相关知识,严格来说,Base64只能算是一种编码方式而非加密算法,这一篇要说的MD5,其实也不算是加密算法,而是一种哈希算法,即将目标文本转化为固定长度,不可逆的字符 ...

  4. java单向加密算法小结(1)--Base64算法

    从这一篇起整理一下常见的加密算法以及在java中使用的demo,首先从最简单的开始. 简单了解 Base64严格来说并不是一种加密算法,而是一种编码/解码的实现方式. 我们都知道,数据在计算机网络之间 ...

  5. [Java 安全]加密算法

    Base64编码 算法简述 定义 Base64内容传送编码是一种以任意8位字节序列组合的描述形式,这种形式不易被人直接识别. Base64是一种很常见的编码规范,其作用是将二进制序列转换为人类可读的A ...

  6. java基本加密算法

    简单的java加密算法有: BASE64 严格地说,属于编码格式,而非加密算法 MD5(Message Digest algorithm 5,信息摘要算法) SHA(Secure Hash Algor ...

  7. JAVA 上加密算法的实现用例---转载

    通常 , 使用的加密算法 比较简便高效 , 密钥简短,加解密速度快,破译极其困难.本文介绍了 MD5/SHA1,DSA,DESede/DES,Diffie-Hellman 的使用. 第 1 章基础知识 ...

  8. Java中加密算法介绍及其实现

    1.Base64编码算法 Base64简介 Base64是网络上最常见的用于传输8Bit字节码的编码方式之一,Base64就是一种基于64个可打印字符来表示二进制数据的方法.可查看RFC2045-RF ...

  9. JAVA 上加密算法的实现用例,MessageDigest介绍

    第 1 章基础知识 1.1. 单钥密码体制 单钥密码体制是一种传统的加密算法,是指信息的发送方和接收方共同使用同一把密钥进行加解密. 通常 , 使用的加密算法 比较简便高效 , 密钥简短,加解密速度快 ...

随机推荐

  1. HTML5七巧板canvas绘图(复习)

    <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <m ...

  2. ExtPager ,分页

    package cn.edu.hbcf.common.vo; public class ExtPager { private Integer start; private Integer limit; ...

  3. .net , java webSocket 连接 Socket.io (1.4.4版本) 问题

    .net版Socketio4net类库和java版socket.io-java-client类库 连接socket.io 1.4版本都不行,网上大多是socket.io 0.9版本的,socket.i ...

  4. 让一个 csproj 项目指定多个开发框架[转]

    原贴:https://walterlv.gitee.io/post/configure-projects-to-target-multiple-platforms.html 可移植类库.共享项目..N ...

  5. FastDFS 常见问题

    FastDFS 常见问题 Q:/fdfs_trackerd: error while loading shared libraries: libevent-1.4.so.2: cannot open ...

  6. 用HTML创建表格

    本章目标:了解掌握表格的基本结构<table><tr><th><td> 掌握跨行.跨列属性colspan rowspan 掌握表格相关修饰属性borde ...

  7. 获取一个Assembly中的命名空间列表

    通过System.Reflection.Assembly类中提供的方法和属性不能直接获取组件中的命名空间列表.但有方法可以直接获得Assembly中的所有类型,我们便可以通过获取的类型来得到命名空间名 ...

  8. H.264 Profile

    提到High Profile H.264解码许多人并不了解,那么到底什么是High Profile H.264解码?其应用效果又是如何呢?  作为行业标准,H.264编码体系定义了4种不同的Profi ...

  9. uva748 - Exponentiation 高精度小数的幂运算

    uva748 - Exponentiation   Exponentiation  Problems involving the computation of exact values of very ...

  10. LBP纹理特征

    LBP-Local Binary Pattern,局部二值模式. 灰度不变性 改进:圆形LBP.旋转不变性 MB-LBP特征,多尺度Multiscale Block LBP: [转载自] 目标检测的图 ...