public class AesEncryptUtils {

private static final String KEY = "d7585fde114abcda";

private static final String ALGORITHMSTR = "AES/CBC/NoPadding";

public static String base64Encode(byte[] bytes) {

return Base64.encodeBase64String(bytes);

}

public static byte[] base64Decode(String base64Code) throws Exception {

return Base64.decodeBase64(base64Code);

}

public static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception {

KeyGenerator kgen = KeyGenerator.getInstance("AES");

kgen.init(128);

Cipher cipher = Cipher.getInstance(ALGORITHMSTR);

cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));

return cipher.doFinal(content.getBytes("utf-8"));

}

public static String aesEncrypt(String content, String encryptKey) throws Exception {

return base64Encode(aesEncryptToBytes(content, encryptKey));

}

public static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception {

KeyGenerator kgen = KeyGenerator.getInstance("AES");

kgen.init(128);

Cipher cipher = Cipher.getInstance(ALGORITHMSTR);

cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));

byte[] decryptBytes = cipher.doFinal(encryptBytes);

return new String(decryptBytes);

}

public static String aesDecrypt(String encryptStr, String decryptKey) throws Exception {

return aesDecryptByBytes(base64Decode(encryptStr), decryptKey);

}

public static void main(String[] args) throws Exception {

String content = "{name:\"lynn\",id:1}";

System.out.println("加密前:" + content);

String encrypt = aesEncrypt(content, KEY);

System.out.println(encrypt.length() + ":加密后:" + encrypt);

String decrypt = aesDecrypt("H9pGuDMV+iJoS8YSfJ2Vx0NYN7v7YR0tMm1ze5zp0WvNEFXQPM7K0k3IDUbYr5ZIckTkTHcIX5Va/cstIPrYEK3KjfCwtOG19l82u+x6soa9FzAtdL4EW5HAFMmpVJVyG3wz/XUysIRCwvoJ20ruEwk07RB3ojc1Vtns8t4kKZE=", "d7b85f6e214abcda");

System.out.println("解密后:" + decrypt);

}

}

public class RSAUtils {

public static final String CHARSET = "UTF-8";

public static final String RSA_ALGORITHM = "RSA";

public static Map createKeys(int keySize){

//为RSA算法创建一个KeyPairGenerator对象

KeyPairGenerator kpg;

try{

kpg = KeyPairGenerator.getInstance(RSA_ALGORITHM);

}catch(NoSuchAlgorithmException e){

throw new IllegalArgumentException("No such algorithm-->[" + RSA_ALGORITHM + "]");

}

//初始化KeyPairGenerator对象,密钥长度

kpg.initialize(keySize);

//生成密匙对

KeyPair keyPair = kpg.generateKeyPair();

//得到公钥

Key publicKey = keyPair.getPublic();

String publicKeyStr = Base64.encodeBase64String(publicKey.getEncoded());

//得到私钥

Key privateKey = keyPair.getPrivate();

String privateKeyStr = Base64.encodeBase64String(privateKey.getEncoded());

Map keyPairMap = new HashMap<>(2);

keyPairMap.put("publicKey", publicKeyStr);

keyPairMap.put("privateKey", privateKeyStr);

return keyPairMap;

}

/**

* 得到公钥

*@param publicKey 密钥字符串(经过base64编码)

*@throws Exception

*/

public static RSAPublicKey getPublicKey(String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException {

//通过X509编码的Key指令获得公钥对象

KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);

X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKey));

RSAPublicKey key = (RSAPublicKey) keyFactory.generatePublic(x509KeySpec);

return key;

}

/**

* 得到私钥

*@param privateKey 密钥字符串(经过base64编码)

*@throws Exception

*/

public static RSAPrivateKey getPrivateKey(String privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException {

//通过PKCS#8编码的Key指令获得私钥对象

KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);

PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));

RSAPrivateKey key = (RSAPrivateKey) keyFactory.generatePrivate(pkcs8KeySpec);

return key;

}

/**

* 公钥加密

*@param data

*@param publicKey

*@return

*/

public static String publicEncrypt(String data, RSAPublicKey publicKey){

try{

Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);

cipher.init(Cipher.ENCRYPT_MODE, publicKey);

return Base64.encodeBase64String(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET), publicKey.getModulus().bitLength()));

}catch(Exception e){

throw new RuntimeException("加密字符串[" + data + "]时遇到异常", e);

}

}

/**

* 私钥解密

*@param data

*@param privateKey

*@return

*/

public static String privateDecrypt(String data, RSAPrivateKey privateKey){

try{

Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);

cipher.init(Cipher.DECRYPT_MODE, privateKey);

return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64.decodeBase64(data), privateKey.getModulus().bitLength()), CHARSET);

}catch(Exception e){

throw new RuntimeException("解密字符串[" + data + "]时遇到异常", e);

}

}

/**

* 私钥加密

*@param data

*@param privateKey

*@return

*/

public static String privateEncrypt(String data, RSAPrivateKey privateKey){

try{

Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);

cipher.init(Cipher.ENCRYPT_MODE, privateKey);

return Base64.encodeBase64String(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET), privateKey.getModulus().bitLength()));

}catch(Exception e){

throw new RuntimeException("加密字符串[" + data + "]时遇到异常", e);

}

}

/**

* 公钥解密

*@param data

*@param publicKey

*@return

*/

public static String publicDecrypt(String data, RSAPublicKey publicKey){

try{

Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);

cipher.init(Cipher.DECRYPT_MODE, publicKey);

return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64.decodeBase64(data), publicKey.getModulus().bitLength()), CHARSET);

}catch(Exception e){

throw new RuntimeException("解密字符串[" + data + "]时遇到异常", e);

}

}

private static byte[] rsaSplitCodec(Cipher cipher, int opmode, byte[] datas, int keySize){

int maxBlock = 0;

if(opmode == Cipher.DECRYPT_MODE){

maxBlock = keySize / 8;

}else{

maxBlock = keySize / 8 - 11;

}

ByteArrayOutputStream out = new ByteArrayOutputStream();

int offSet = 0;

byte[] buff;

int i = 0;

try{

while(datas.length > offSet){

if(datas.length-offSet > maxBlock){

buff = cipher.doFinal(datas, offSet, maxBlock);

}else{

buff = cipher.doFinal(datas, offSet, datas.length-offSet);

}

out.write(buff, 0, buff.length);

i++;

offSet = i * maxBlock;

}

}catch(Exception e){

throw new RuntimeException("加解密阀值为["+maxBlock+"]的数据时发生异常", e);

}

byte[] resultDatas = out.toByteArray();

IOUtils.closeQuietly(out);

return resultDatas;

}

public static void main(String[] args) throws Exception{

Map keyMap = RSAUtils.createKeys(1024);

String publicKey = keyMap.get("publicKey");

String privateKey = "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAJxmWQdpI3R/DcJYaDNy4944o900od1zadHootdrOGHMWF7vw2oyuGzI1N/frmxoVLaUAMrcLMBLMfhPRtP4acnvuOgM4/7RKq5scrAAi/znSVPRDFL5165QeDb64diF2EjDk0KZnRKQ1qXDyKA/XJL7ZMQhhqfeVqQ8G9khKpGzAgMBAAECgYEAj+5AkGlZj6Q9bVUez/ozahaF9tSxAbNs9xg4hDbQNHByAyxzkhALWVGZVk3rnyiEjWG3OPlW1cBdxD5w2DIMZ6oeyNPA4nehYrf42duk6AI//vd3GsdJa6Dtf2has1R+0uFrq9MRhfRunAf0w6Z9zNbiPNSd9VzKjjSvcX7OTsECQQD20kekMToC6LZaZPr1p05TLUTzXHvTcCllSeXWLsjVyn0AAME17FJRcL9VXQuSUK7PQ5Lf5+OpjrCRYsIvuZg9AkEAojdC6k3SqGnbtftLfGHMDn1fe0nTJmL05emwXgJvwToUBdytvgbTtqs0MsnuaOxMIMrBtpbhS6JiB5Idb7GArwJAfKTkmP5jFWT/8dZdBgFfhJGv6FYkEjrqLMSM1QT7VzvStFWtPNYDHC2b8jfyyAkGvpSZb4ljZxUwBbuh5QgM4QJBAJDrV7+lOP62W9APqdd8M2X6gbPON3JC09EW3jaObLKupTa7eQicZsX5249IMdLQ0A43tanez3XXo0ZqNhwT8wcCQQDUubpNLwgAwN2X7kW1btQtvZW47o9CbCv+zFKJYms5WLrVpotjkrCgPeuloDAjxeHNARX8ZTVDxls6KrjLH3lT";

System.out.println("公钥: \n\r" + publicKey);

System.out.println("私钥: \n\r" + privateKey);

System.out.println("公钥加密——私钥解密");

String str = "站在大明门前守卫的禁卫军,事先没有接到\n" +

"有关的命令,但看到大批盛装的官员来临,也就\n" +

"以为确系举行大典,因而未加询问。进大明门即\n" +

"为皇城。文武百官看到端门午门之前气氛平静,\n" +

"城楼上下也无朝会的迹象,既无几案,站队点名\n" +

"的御史和御前侍卫“大汉将军”也不见踪影,不免\n" +

"心中揣测,互相询问:所谓午朝是否讹传?";

System.out.println("\r明文:\r\n" + str);

System.out.println("\r明文大小:\r\n" + str.getBytes().length);

String encodedData = RSAUtils.publicEncrypt(str, RSAUtils.getPublicKey(publicKey));

System.out.println("密文:\r\n" + encodedData);

String decodedData = RSAUtils.privateDecrypt("X4hHPa9NjPd5QJGPus+4+hWmOzbWg7oCJ1+Vc+7dHW81nEhkYnJpFyV5xcDkg70N2Mym+YAJ1PvYY9sQWf9/EkUE61TpUKBmDaGWLjEr3A1f9cKIelqLKLsJGdXEOr7Z55k4vYFvA7N3Vf5KQo3NrouvIT4wR+SjH4tDQ8tNh3JH8BvXLtXqGa2TCK2z1AzHNgYzcLCrqDasd7UDHRPZPiW4thktM/whjBn0tU9B/kKjAjLuYttKLEmy5nT7v7u16aZ6ehkk+kzvuCXF%2B3RsqraISDPbsTki2agJyqsycRx3w7CvKRyUbZhFaNcWigOwmcbZVoiom+ldh7Vh6HYqDA==", RSAUtils.getPrivateKey(privateKey));

System.out.println("解密后文字: \r\n" + decodedData);

}

}

/**

* 私钥输入参数(其实就是客户端通过服务端返回的公钥加密后的客户端自己生成的公钥)

*/

public class KeyRequest {

/**

* 客户端自己生成的加密后公钥

*/

@NotNull

private String clientEncryptPublicKey;

public String getClientEncryptPublicKey() {

return clientEncryptPublicKey;

}

public void setClientEncryptPublicKey(String clientEncryptPublicKey) {

this.clientEncryptPublicKey = clientEncryptPublicKey;

}

}

/**

* RSA生成的公私钥输出参数

*/

public class RSAResponse extends BaseResponse{

private String serverPublicKey;

private String serverPrivateKey;

public static class Builder{

private String serverPublicKey;

private String serverPrivateKey;

public Builder setServerPublicKey(String serverPublicKey){

this.serverPublicKey = serverPublicKey;

return this;

}

public Builder setServerPrivateKey(String serverPrivateKey){

this.serverPrivateKey = serverPrivateKey;

return this;

}

public RSAResponse build(){

return new RSAResponse(this);

}

}

public static Builder options(){

return new Builder();

}

public RSAResponse(Builder builder){

this.serverPrivateKey = builder.serverPrivateKey;

this.serverPublicKey = builder.serverPublicKey;

}

public String getServerPrivateKey() {

return serverPrivateKey;

}

public String getServerPublicKey() {

return serverPublicKey;

}

}

/**

* 私钥输出参数

*/

public class KeyResponse extends BaseResponse{

/**

* 整个系统所有加密算法共用的密钥

*/

private String key;

public static class Builder{

private String key;

public Builder setKey(String key){

this.key = key;

return this;

}

public KeyResponse build(){

return new KeyResponse(this);

}

}

public static Builder options(){

return new Builder();

}

private KeyResponse(Builder builder){

this.key = builder.key;

}

public String getKey() {

return key;

}

}

/**

* API传输加解密相关接口

*/

public interface EncryptOpenService {

/**

* 生成RSA公私钥

*@return

*/

SingleResult getRSA();

/**

* 获得加解密用的密钥

*@param request

*@return

*/

SingleResult getKey(KeyRequest request) throws Exception;

}

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐