您的位置:首页 > 编程语言 > Java开发

Java基于AES的加密与解密

2016-11-01 17:15 344 查看
基于AES的加密与解密,加密与解密都需要指定相关的key。

1、加密与解密代码

package com.ganymede.utils;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;

/**
* Created by wuke on 2016/11/1.
*/
public class EnAesCode {
static private byte[] codes = new byte[256];
private static final String ALGORITHM_KEY = "AES";
private static final String ALGORITHM_ENCODING = "UTF-8";

static {
for (int i = 0; i < 256; i++)
codes[i] = -1;
for (int i = 'A'; i <= 'Z'; i++)
codes[i] = (byte) (i - 'A');
for (int i = 'a'; i <= 'z'; i++)
codes[i] = (byte) (26 + i - 'a');
for (int i = '0'; i <= '9'; i++)
codes[i] = (byte) (52 + i - '0');
codes['+'] = 62;
codes['/'] = 63;
}

/**
* 将base64编码的数据解码成原始数据
*
* @param data
* @return
*/
static public byte[] decode(byte[] data) {
int len = ((data.length + 3) / 4) * 3;
if (data.length > 0 & data[data.length - 1] == '=')
--len;
if (data.length > 1 & data[data.length - 2] == '=')
--len;
byte[] out = new byte[len];
int shift = 0;
int accum = 0;
int index = 0;
for (int ix = 0; ix < data.length; ix++) {
int value = codes[data[ix] & 0xFF];
if (value >= 0) {
accum <<= 6;
shift += 6;
accum |= value;
if (shift >= 8) {
shift -= 8;
out[index++] = (byte) ((accum >> shift) & 0xff);
}
}
}
if (index != out.length) {
out = null;
}

return out;
}

/**
* 解密字符串
* 需提供相关密码
*
* @param content
* @param strKey
* @return
*/
public static String decrypt(String content, String strKey) {
try {
byte[] keyBytes = Arrays.copyOf(strKey.getBytes("ASCII"), 16);
SecretKey key = new SecretKeySpec(keyBytes, ALGORITHM_KEY);
Cipher cipher = Cipher.getInstance(ALGORITHM_KEY);
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] cleartext = decode(content.getBytes(ALGORITHM_ENCODING));
byte[] ciphertextBytes = cipher.doFinal(cleartext);
return new String(ciphertextBytes);

} catch (Exception ex) {
return null;
}
}

/**
* 加密字符串
* 需提供相关密码
*
* @param mobile
* @param strKey
* @return
*/
public static String encrypt(String mobile, String strKey) {
if (mobile == null || "".equals(mobile)) {
return mobile;
}
byte[] mobileKeyBytes = null;
try {
mobileKeyBytes = Arrays.copyOf(strKey.getBytes("ASCII"), 16);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}

byte[] encryptBytes = enCode(mobile, mobileKeyBytes);

if (encryptBytes == null) {
// 加密报错了
return mobile;
}
// 返回带特定标识的密文
// 进行Base64编码
return new StringBuilder("").append(Base64.encodeBase64String(encryptBytes)).toString().replaceAll("\n", "");

}

/**
* AES加密
*
* @param clearText
* @param keyBytes
* @return
*/
private static byte[] enCode(String clearText, byte[] keyBytes) {
try {
SecretKey key = new SecretKeySpec(keyBytes, ALGORITHM_KEY);
Cipher cipher = Cipher.getInstance(ALGORITHM_KEY);
cipher.init(Cipher.ENCRYPT_MODE, key);

byte[] cleartext = clearText.getBytes(ALGORITHM_ENCODING);
byte[] ciphertextBytes = cipher.doFinal(cleartext);

return ciphertextBytes;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

public static void main(String[] args) {
String enCode = EnAesCode.encrypt("18912345678", "abc");
System.out.println(enCode);

String denCode = EnAesCode.decrypt(enCode, "abc");
System.out.println(denCode);

}
}


2、 项目的pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion>

<groupId>com.ganymede</groupId>
<artifactId>javaee</artifactId>
<version>1.0-SNAPSHOT</version>

<!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
<dependencies>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
</dependency>
</dependencies>

<!-- maven官方 http://repo1.maven.org/maven2/http://repo2.maven.org/maven2/ (延迟低一些) -->
<repositories>
<repository>
<id>central</id>
<name>Maven Repository Switchboard</name>
<layout>default</layout>
<url>http://repo2.maven.org/maven2</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>

</project>

3、加密与解密时,只要对应好相关的key就好,也不容易被破解。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: