Base64Utils工具类:
package com.rsa.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import com.sun.org.apache.xml.internal.security.utils.Base64;
/**
* <p>
* BASE64编码解码工具包
* </p>
* <p>
* 依赖javabase64-1.3.1.jar
* </p>
*
* @author IceWee
* @date 2012-5-19
* @version 1.0
*/
public class Base64Utils {
/**
* 文件读取缓冲区大小
*/
private static final int CACHE_SIZE = 1024;
/**
* <p>
* BASE64字符串解码为二进制数据
* </p>
*
* @param base64
* @return
* @throws Exception
*/
public static byte[] decode(String base64) throws Exception {
return Base64.decode(base64.getBytes());
}
/**
* <p>
* 二进制数据编码为BASE64字符串
* </p>
*
* @param bytes
* @return
* @throws Exception
*/
public static String encode(byte[] bytes) throws Exception {
return new String(Base64.encode(bytes));
}
/**
* <p>
* 将文件编码为BASE64字符串
* </p>
* <p>
* 大文件慎用,可能会导致内存溢出
* </p>
*
* @param filePath 文件绝对路径
* @return
* @throws Exception
*/
public static String encodeFile(String filePath) throws Exception {
byte[] bytes = fileToByte(filePath);
return encode(bytes);
}
/**
* <p>
* BASE64字符串转回文件
* </p>
*
* @param filePath 文件绝对路径
* @param base64 编码字符串
* @throws Exception
*/
public static void decodeToFile(String filePath, String base64) throws Exception {
byte[] bytes = decode(base64);
byteArrayToFile(bytes, filePath);
}
/**
* <p>
* 文件转换为二进制数组
* </p>
*
* @param filePath 文件路径
* @return
* @throws Exception
*/
public static byte[] fileToByte(String filePath) throws Exception {
byte[] data = new byte[0];
File file = new File(filePath);
if (file.exists()) {
FileInputStream in = new FileInputStream(file);
ByteArrayOutputStream out = new ByteArrayOutputStream(2048);
byte[] cache = new byte[CACHE_SIZE];
int nRead = 0;
while ((nRead = in.read(cache)) != -1) {
out.write(cache, 0, nRead);
out.flush();
}
out.close();
in.close();
data = out.toByteArray();
}
return data;
}
/**
* <p>
* 二进制数据写文件
* </p>
*
* @param bytes 二进制数据
* @param filePath 文件生成目录
*/
public static void byteArrayToFile(byte[] bytes, String filePath) throws Exception {
InputStream in = new ByteArrayInputStream(bytes);
File destFile = new File(filePath);
if (!destFile.getParentFile().exists()) {
destFile.getParentFile().mkdirs();
}
destFile.createNewFile();
OutputStream out = new FileOutputStream(destFile);
byte[] cache = new byte[CACHE_SIZE];
int nRead = 0;
while ((nRead = in.read(cache)) != -1) {
out.write(cache, 0, nRead);
out.flush();
}
out.close();
in.close();
}
}
1、工具类:
package com.util;
import java.io.UnsupportedEncodingException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.text.SimpleDateFormat;
import com.core.flow.util.Base64Utils;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
public class RSAHelper {
public static final String KEY_ALGORITHM = "RSA";
public static final String PUBLIC_KEY = "PublicKey";
public static final String PRIVATE_KEY = "PrivateKey";
private static final String SIGNATURE_ALGORITHM = "MD5withRSA";
public RSAHelper() {
}
/**
*
* @param keyMap
* 获取公私钥对
* @return
* @throws Exception
* @throws UnsupportedEncodingException
*
*/
public static Map generateKeyPair() throws Exception{
boolean result = false;
Map keyMap = new HashMap() ;
KeyPairGenerator keyPairGenerator = null;
try {
keyPairGenerator = KeyPairGenerator.getInstance("RSA");
result = true;
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(RSAHelper.class.getName()).log(Level.SEVERE, null,
ex);
}
if (result) {
SecureRandom secureRandom = new SecureRandom();
String currentDateTime = new SimpleDateFormat("yyyyMMddHHmmssSSS")
.format(new Date());
secureRandom.setSeed(currentDateTime.getBytes());
keyPairGenerator.initialize(1024, secureRandom);
KeyPair keyPair = keyPairGenerator.genKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
keyMap.put(RSAHelper.PUBLIC_KEY,Base64Utils.encode(publicKey.getEncoded()));
keyMap.put(RSAHelper.PRIVATE_KEY, Base64Utils.encode(privateKey.getEncoded()));
return keyMap;
}
return keyMap;
}
/**
*
* @param strData 源数据字符串
* @param strPrivateKeyBytes 签名私钥
* @return String
* 通过私钥签名
* @throws Exception
*/
public static String sign(String strData, String strPrivateKeyBytes) throws Exception {
byte[] signedData = null;
byte[] privateKeyBytes =Base64Utils.decode(strPrivateKeyBytes);
try {
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(
privateKeyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory
.generatePrivate(pkcs8EncodedKeySpec);
Signature signature = Signature.getInstance(RSAHelper.SIGNATURE_ALGORITHM);
signature.initSign(privateKey);
byte[] data = strData.getBytes();
signature.update(data);
signedData = signature.sign();
} catch (Exception ex) {
Logger.getLogger(RSAHelper.class.getName()).log(Level.SEVERE, null,
ex);
}
return Base64Utils.encode(signedData);
}
/**
*
* @param strData 数据明文串
* @param strPublicKeyBytes 验签公钥
* @param strDataSignature 签名数据
* @return boolean
* 通过公钥验签
* @throws Exception
*
*/
public static boolean verify(String strData,
String strPublicKeyBytes, String strDataSignature) throws Exception {
boolean result = false;
byte[] publicKeyBytes =Base64Utils.decode(strPublicKeyBytes);
try {
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(
publicKeyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
Signature signature = Signature.getInstance(RSAHelper.SIGNATURE_ALGORITHM);
signature.initVerify(publicKey);
byte[] data = strData.getBytes();
signature.update(data);
byte[] dataSignature =Base64Utils.decode(strDataSignature);
result = signature.verify(dataSignature);
} catch (Exception ex) {
Logger.getLogger(RSAHelper.class.getName()).log(Level.SEVERE, null,
ex);
}
return result;
}
}
2、测试类:
package com.core.flow.util;
import java.util.Map;
public class RsaTest {
public static void main(String args[]) throws Exception{
//待签名数据
String strData = "这是一个测试数据,这是一个测试数据,这是一个测试数据。重要的事情说三遍";
//生成公私密钥对
Map keyMap = RSAHelper.generateKeyPair();
System.out.println("公钥:"+ (String) keyMap.get(RSAHelper.PUBLIC_KEY));
System.out.println("私钥:"+ (String) keyMap.get(RSAHelper.PRIVATE_KEY));
//数据签名
String signData = RSAHelper.sign(strData, (String)keyMap.get(RSAHelper.PRIVATE_KEY));
//签名数据
System.out.println(signData);
//验签
boolean b = RSAHelper.verify(strData, (String)keyMap.get(RSAHelper.PUBLIC_KEY), signData);
//验签结果
System.out.println(b);
}
}
有问题可以给我留言哦!!!