java基础常用非对称加密RSA ,AES加解密和 SIGN签名验签

package com.*.bec.controlling.util;

import com.*.*.component.id.idworker.IdWorker;

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

import org.apache.poi.util.SystemOutLogger;

 

import java.security.*;

import java.security.spec.PKCS8EncodedKeySpec;

import java.security.spec.X509EncodedKeySpec;

import java.util.HashMap;

import java.util.Map;

 

import javax.crypto.Cipher;

 

/**

* Created by humf.需要依赖 commons-codec 包

*/

public class RSACoder {

public static final String KEY_ALGORITHM = "RSA";

public static final String SIGNATURE_ALGORITHM = "MD5withRSA";

 

private static final String PUBLIC_KEY = "RSAPublicKey";

private static final String PRIVATE_KEY = "RSAPrivateKey";

 

public static byte[] decryptBASE64(String key) {

return Base64.decodeBase64(key);

}

 

public static String encryptBASE64(byte[] bytes) {

return Base64.encodeBase64String(bytes);

}

 

/**

* 用私钥对信息生成数字签名

*

* @param data 加密数据

* @param privateKey 私钥

* @return

* @throws Exception

*/

public static String sign(byte[] data, String privateKey) throws Exception {

// 解密由base64编码的私钥

byte[] keyBytes = decryptBASE64(privateKey);

// 构造PKCS8EncodedKeySpec对象

PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);

// KEY_ALGORITHM 指定的加密算法

KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

// 取私钥匙对象

PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);

// 用私钥对信息生成数字签名

Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);

signature.initSign(priKey);

signature.update(data);

return encryptBASE64(signature.sign());

}

 

/**

* 校验数字签名

*

* @param data 加密数据

* @param publicKey 公钥

* @param sign 数字签名

* @return 校验成功返回true 失败返回false

* @throws Exception

*/

public static boolean verify(byte[] data, String publicKey, String sign)

throws Exception {

// 解密由base64编码的公钥

byte[] keyBytes = decryptBASE64(publicKey);

// 构造X509EncodedKeySpec对象

X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);

// KEY_ALGORITHM 指定的加密算法

KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

// 取公钥匙对象

PublicKey pubKey = keyFactory.generatePublic(keySpec);

Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);

signature.initVerify(pubKey);

signature.update(data);

// 验证签名是否正常

return signature.verify(decryptBASE64(sign));

}

 

public static byte[] decryptByPrivateKey(byte[] data, String key) throws Exception{

// 对密钥解密

byte[] keyBytes = decryptBASE64(key);

// 取得私钥

PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);

KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);

// 对数据解密

Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());

cipher.init(Cipher.DECRYPT_MODE, privateKey);

return cipher.doFinal(data);

}

 

/**

* 解密<br>

* 用私钥解密

*

* @param data

* @param key

* @return

* @throws Exception

*/

public static byte[] decryptByPrivateKey(String data, String key)

throws Exception {

return decryptByPrivateKey(decryptBASE64(data),key);

}

 

/**

* 解密<br>

* 用公钥解密

*

* @param data

* @param key

* @return

* @throws Exception

*/

public static byte[] decryptByPublicKey(byte[] data, String key)

throws Exception {

// 对密钥解密

byte[] keyBytes = decryptBASE64(key);

// 取得公钥

X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);

KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

Key publicKey = keyFactory.generatePublic(x509KeySpec);

// 对数据解密

Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());

cipher.init(Cipher.DECRYPT_MODE, publicKey);

return cipher.doFinal(data);

}

 

/**

* 加密<br>

* 用公钥加密

*

* @param data

* @param key

* @return

* @throws Exception

*/

public static byte[] encryptByPublicKey(String data, String key)

throws Exception {

// 对公钥解密

byte[] keyBytes = decryptBASE64(key);

// 取得公钥

X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);

KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

Key publicKey = keyFactory.generatePublic(x509KeySpec);

// 对数据加密

Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());

cipher.init(Cipher.ENCRYPT_MODE, publicKey);

return cipher.doFinal(data.getBytes());

}

 

/**

* 加密<br>

* 用私钥加密

*

* @param data

* @param key

* @return

* @throws Exception

*/

public static byte[] encryptByPrivateKey(byte[] data, String key)

throws Exception {

// 对密钥解密

byte[] keyBytes = decryptBASE64(key);

// 取得私钥

PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);

KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);

// 对数据加密

Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());

cipher.init(Cipher.ENCRYPT_MODE, privateKey);

return cipher.doFinal(data);

}

 

/**

* 取得私钥

*

* @param keyMap

* @return

* @throws Exception

*/

public static String getPrivateKey(Map<String, Key> keyMap)

throws Exception {

Key key = (Key) keyMap.get(PRIVATE_KEY);

return encryptBASE64(key.getEncoded());

}

 

/**

* 取得公钥

*

* @param keyMap

* @return

* @throws Exception

*/

public static String getPublicKey(Map<String, Key> keyMap)

throws Exception {

Key key = keyMap.get(PUBLIC_KEY);

return encryptBASE64(key.getEncoded());

}

 

/**

* 初始化密钥

*

* @return

* @throws Exception

*/

public static Map<String, Key> initKey() throws Exception {

KeyPairGenerator keyPairGen = KeyPairGenerator

.getInstance(KEY_ALGORITHM);

keyPairGen.initialize(1024);

KeyPair keyPair = keyPairGen.generateKeyPair();

Map<String, Key> keyMap = new HashMap(2);

keyMap.put(PUBLIC_KEY, keyPair.getPublic());// 公钥

keyMap.put(PRIVATE_KEY, keyPair.getPrivate());// 私钥

return keyMap;

}

 

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

Map<String, Key> keyMap = initKey();

String publicKey1 = getPublicKey(keyMap);

String privateKey1 = getPrivateKey(keyMap);

Map<String, Key> keyMap2 = initKey();

String publicKey2 = getPublicKey(keyMap2);

String privateKey2 = getPrivateKey(keyMap2);

System.out.println(keyMap);

System.out.println("--RSA公钥如下--甲方: ");

System.out.println("公钥1:"+publicKey1);

System.out.println("私钥1:"+privateKey1);

 

System.out.println("--RSA公钥如下--乙方: ");

System.out.println("公钥2:"+publicKey2);

System.out.println("私钥2:"+privateKey2);

System.out.println("#### 甲方持有:【publicKey2,privateKey1】 乙方持有:【publicKey1,privateKey2】####");

System.out.println("—————————开始————甲方加密数据———————");

//byte[] encryptByPrivateKey = encryptByPrivateKey("{hello:world}".getBytes(),privateKey);

byte[] encryptByPublicKey = encryptByPublicKey("{嗨喽:沃德}",publicKey2);

// System.out.println("----------私钥加密数据后---------------");

// System.out.println(new String(encryptByPrivateKey).getBytes("UTF-8"));

System.out.println("----1------公钥加密数据后---------------");

System.out.println(new String(encryptByPublicKey).getBytes("UTF-8"));

//随机数最为AES加密公钥

Long miyao = new IdWorker().nextId();

String aesString = AESUtils2.aesEncrypt(new String(encryptByPublicKey),String.valueOf(miyao));

System.out.println("------------------AES加密 公钥为:【"+miyao+" 】加密后得到: "+aesString);

System.out.println("------------------base64后-----------------------");

System.out.println(AESUtils2.base64Encode(aesString.getBytes("UTF-8")));

System.out.println("----2-------私钥对加密数据生成数字签名-----------【sign】");

String sign = sign(encryptByPublicKey,privateKey1);

System.out.println(sign);

System.out.println("—————————中间————乙方解密数据———————");

System.out.println("----3-----校验:信息,公钥,数字签名---------------");

boolean verify = verify(encryptByPublicKey,publicKey1,sign);

System.out.println(verify);

// System.out.println("------------公钥解密----------------");

// byte[] decryptByPublicKey = decryptByPublicKey(encryptByPrivateKey,publicKey);

// System.out.println(new String(decryptByPublicKey));

System.out.println("----4---------私钥解密-----------------");

byte[] decryptByPrivateKey = decryptByPrivateKey(encryptByPublicKey,privateKey2);

 

System.out.println(new String(decryptByPrivateKey));

//阐言思路,RSA对AES对称加密的(随机)密钥进行非对称加密,用对方的公钥加密,对方用自己的私钥解密。过程为AES加密后进行base64转码

}

}

 

 

 

#########################################################################################

 

 

package com.*.bec.controlling.util;

 

import com.*.bec.controlling.restfulservice.FtpService;

import sun.misc.BASE64Decoder;

import sun.misc.BASE64Encoder;

 

import javax.crypto.Cipher;

import javax.crypto.spec.IvParameterSpec;

import javax.crypto.spec.SecretKeySpec;

import java.io.*;

import java.util.Date;

import java.util.List;

import java.util.UUID;

 

public class AESUtils2 {

 

 

//第二段摘录

/**

* 加密

* @param content

* @param strKey

* @return

* @throws Exception

*/

public static byte[] encrypt2(String content,String strKey ) throws Exception {

SecretKeySpec skeySpec = getKey(strKey);

//Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

Cipher cipher =Cipher.getInstance("AES/CTR/NoPadding");

IvParameterSpec iv = new IvParameterSpec("0102030405060708".getBytes());

cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);

byte[] encrypted = cipher.doFinal(content.getBytes());

return encrypted;

}

 

/**

* 解密

* @param strKey

* @param content

* @return

* @throws Exception

*/

public static String decrypt(byte[] content,String strKey ) throws Exception {

SecretKeySpec skeySpec = getKey(strKey);

Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");

IvParameterSpec iv = new IvParameterSpec("0102030405060708".getBytes());

cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);

byte[] original = cipher.doFinal(content);

String originalString = new String(original);

return originalString;

}

 

private static SecretKeySpec getKey(String strKey) throws Exception {

byte[] arrBTmp = strKey.getBytes();

byte[] arrB = new byte[16]; // 创建一个空的16位字节数组(默认值为0)

 

for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {

arrB[i] = arrBTmp[i];

}

 

SecretKeySpec skeySpec = new SecretKeySpec(arrB, "AES");

 

return skeySpec;

}

 

/**

* base 64 encode

* @param bytes 待编码的byte[]

* @return 编码后的base 64 code

*/

public static String base64Encode(byte[] bytes){

return new BASE64Encoder().encode(bytes);

}

 

/**

* base 64 decode

* @param base64Code 待解码的base 64 code

* @return 解码后的byte[]

* @throws Exception

*/

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

return base64Code.isEmpty() ? null : new BASE64Decoder().decodeBuffer(base64Code);

}

 

/**

* AES加密为base 64 code

* @param content 待加密的内容

* @param encryptKey 加密密钥

* @return 加密后的base 64 code

* @throws Exception

*/

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

return base64Encode(encrypt2(content, encryptKey));

}

/**

* 将base 64 code AES解密

* @param encryptStr 待解密的base 64 code

* @param decryptKey 解密密钥

* @return 解密后的string

* @throws Exception

*/

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

return encryptStr.isEmpty() ? null : decrypt(base64Decode(encryptStr), decryptKey);

}

// 写一个测试,看下效果:

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

// for(int i=0;i<2;i++){

// String test = "{'repairPhone':'18547854787','customPhone':'12365478965','captchav':'58m7','hello':'world',}";

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

//

// // String key = "123456";

// String key = UUID.randomUUID().toString().replaceAll("-", "");;//随机公钥

// System.out.println("【随机密钥】:" + key);

// System.out.println("加密后____:"+encrypt2(test, key));

//

压缩

//

// InputStream is = new ByteArrayInputStream(encrypt2(test, key));

// byte[] yasuodata = new byte[is.available()];

// System.out.println("加密压缩后____:" + GzipUtils.gzip(yasuodata));

// System.out.println("加密压缩base64后____:" + base64Encode(GzipUtils.gzip(yasuodata)));

//

// String encrypt = aesEncrypt(test, key);

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

对key进行RSA加密

// RSAdemo rsa=new RSAdemo();

// rsa.generateKey();

// byte[] data=rsa.encrypt("12345".getBytes());

// Long startTimea = System.currentTimeMillis();

// byte[] data1=rsa.decrypt(data);

// Long endTimeb =System.currentTimeMillis();

// System.out.println("RSA解秘时间:" + (endTimeb - startTimea) + "ms");

String str=new String(data1);

// System.out.println("【RSA公钥加密后结果】:"+data);

// System.out.println("【RSA私钥解密后结果】:"+data1);

//

// Long startTime = System.currentTimeMillis();

// String decrypt = aesDecrypt(encrypt, key);

// Long endTime =System.currentTimeMillis();

// System.out.println("AES解秘时间:" + (endTime - startTime) + "ms");

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

// System.out.println("_________________________________________");

// new RSAdemo().generateKey();

// System.out.println( new FtpUtil().getIp());

 

FtpOperation ftpOperation = new FtpOperation();

FtpUtil ftpUtil = new FtpUtil();

List<String> fileList = ftpUtil.getFileNameList("");

System.out.println(fileList);

InputStream bis = ftpUtil.downloadFile(fileList.get(0));//下载文件方法

/* byte[] bytes = new byte[0];

bytes = new byte[in.available()];

in.read(bytes);*/

//BufferedInputStream bis = new BufferedInputStream(inputStream);乱码

// InputStreamReader bis = new InputStreamReader(inputStream,"UTF-8");导致乱码

ByteArrayOutputStream buf = new ByteArrayOutputStream();

int result = bis.read();

while(result != -1) {

buf.write((byte) result);

result = bis.read();

}

String str = buf.toString("utf-8");

System.out.println(str);

//成功读取数据下载转为String

 

//unzip

new UnZip().UnZip("","");

 

 

 

//常用是随机密钥进行非对称加密,用随机密钥对称加密数据报文 }

 

 

}

}

 

 


版权声明:本文为m0_37549763原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。