/**
* RSA算法,实现数据的加密解密。
* @author ShaoJiang
*
*/
public class RSAUtil {
private static Cipher cipher
static{
try {
cipher = Cipher.getInstance("RSA")
} catch (NoSuchAlgorithmException e) {
e.printStackTrace()
} catch (NoSuchPaddingException e) {
e.printStackTrace()
}
}
/**
* 生成密钥对
* @param filePath 生成密钥的路径誉春
* @return
*/
public static Map<String,String>generateKeyPair(String filePath){
try {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA")
// 密钥位纯虚笑数
keyPairGen.initialize(1024)
// 密钥对
KeyPair keyPair = keyPairGen.generateKeyPair()
// 公做含钥
PublicKey publicKey = (RSAPublicKey) keyPair.getPublic()
// 私钥
PrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate()
//得到公钥字符串
String publicKeyString = getKeyString(publicKey)
//得到私钥字符串
String privateKeyString = getKeyString(privateKey)
FileWriter pubfw = new FileWriter(filePath+"/publicKey.keystore")
FileWriter prifw = new FileWriter(filePath+"/privateKey.keystore")
BufferedWriter pubbw = new BufferedWriter(pubfw)
BufferedWriter pribw = new BufferedWriter(prifw)
pubbw.write(publicKeyString)
pribw.write(privateKeyString)
pubbw.flush()
pubbw.close()
pubfw.close()
pribw.flush()
pribw.close()
prifw.close()
//将生成的密钥对返回
Map<String,String>map = new HashMap<String,String>()
map.put("publicKey",publicKeyString)
map.put("privateKey",privateKeyString)
return map
} catch (Exception e) {
e.printStackTrace()
}
return null
}
/**
* 得到公钥
*
* @param key
*密钥字符串(经过base64编码)
* @throws Exception
*/
public static PublicKey getPublicKey(String key) throws Exception {
byte[] keyBytes
keyBytes = (new BASE64Decoder()).decodeBuffer(key)
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes)
KeyFactory keyFactory = KeyFactory.getInstance("RSA")
PublicKey publicKey = keyFactory.generatePublic(keySpec)
return publicKey
}
/**
* 得到私钥
*
* @param key
*密钥字符串(经过base64编码)
* @throws Exception
*/
public static PrivateKey getPrivateKey(String key) throws Exception {
byte[] keyBytes
keyBytes = (new BASE64Decoder()).decodeBuffer(key)
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes)
KeyFactory keyFactory = KeyFactory.getInstance("RSA")
PrivateKey privateKey = keyFactory.generatePrivate(keySpec)
return privateKey
}
/**
* 得到密钥字符串(经过base64编码)
*
* @return
*/
public static String getKeyString(Key key) throws Exception {
byte[] keyBytes = key.getEncoded()
String s = (new BASE64Encoder()).encode(keyBytes)
return s
}
/**
* 使用公钥对明文进行加密,返回BASE64编码的字符串
* @param publicKey
* @param plainText
* @return
*/
public static String encrypt(PublicKey publicKey,String plainText){
try {
cipher.init(Cipher.ENCRYPT_MODE, publicKey)
byte[] enBytes = cipher.doFinal(plainText.getBytes())
return (new BASE64Encoder()).encode(enBytes)
} catch (InvalidKeyException e) {
e.printStackTrace()
} catch (IllegalBlockSizeException e) {
e.printStackTrace()
} catch (BadPaddingException e) {
e.printStackTrace()
}
return null
}
/**
* 使用keystore对明文进行加密
* @param publicKeystore 公钥文件路径
* @param plainText 明文
* @return
*/
public static String encrypt(String publicKeystore,String plainText){
try {
FileReader fr = new FileReader(publicKeystore)
BufferedReader br = new BufferedReader(fr)
String publicKeyString=""
String str
while((str=br.readLine())!=null){
publicKeyString+=str
}
br.close()
fr.close()
cipher.init(Cipher.ENCRYPT_MODE,getPublicKey(publicKeyString))
byte[] enBytes = cipher.doFinal(plainText.getBytes())
return (new BASE64Encoder()).encode(enBytes)
} catch (InvalidKeyException e) {
e.printStackTrace()
} catch (IllegalBlockSizeException e) {
e.printStackTrace()
} catch (BadPaddingException e) {
e.printStackTrace()
} catch (Exception e) {
e.printStackTrace()
}
return null
}
/**
* 使用私钥对明文密文进行解密
* @param privateKey
* @param enStr
* @return
*/
public static String decrypt(PrivateKey privateKey,String enStr){
try {
cipher.init(Cipher.DECRYPT_MODE, privateKey)
byte[] deBytes = cipher.doFinal((new BASE64Decoder()).decodeBuffer(enStr))
return new String(deBytes)
} catch (InvalidKeyException e) {
e.printStackTrace()
} catch (IllegalBlockSizeException e) {
e.printStackTrace()
} catch (BadPaddingException e) {
e.printStackTrace()
} catch (IOException e) {
e.printStackTrace()
}
return null
}
/**
* 使用keystore对密文进行解密
* @param privateKeystore 私钥路径
* @param enStr 密文
* @return
*/
public static String decrypt(String privateKeystore,String enStr){
try {
FileReader fr = new FileReader(privateKeystore)
BufferedReader br = new BufferedReader(fr)
String privateKeyString=""
String str
while((str=br.readLine())!=null){
privateKeyString+=str
}
br.close()
fr.close()
cipher.init(Cipher.DECRYPT_MODE, getPrivateKey(privateKeyString))
byte[] deBytes = cipher.doFinal((new BASE64Decoder()).decodeBuffer(enStr))
return new String(deBytes)
} catch (InvalidKeyException e) {
e.printStackTrace()
} catch (IllegalBlockSizeException e) {
e.printStackTrace()
} catch (BadPaddingException e) {
e.printStackTrace()
} catch (IOException e) {
e.printStackTrace()
} catch (Exception e) {
e.printStackTrace()
}
return null
}
}
一个比较简单的实现:一个三个类KeyGenerater生成公钥私钥对御颤,Signaturer类使用私钥签名,SignProvider用公钥验证。公钥和私钥使用Base64加密Base64这个类也在博客里面public class KeyGenerater {
private byte[] priKey
private byte[] pubKey
public void generater() {
try {
Java.security.KeyPairGenerator keygen = java.security.KeyPairGenerator
.getInstance("RSA")
SecureRandom secrand = new SecureRandom()
secrand.setSeed("syj".getBytes())// 初始化随机产仔拆裂生器
keygen.initialize(1024, secrand)
KeyPair keys = keygen.genKeyPair()
PublicKey pubkey = keys.getPublic()
PrivateKey prikey = keys.getPrivate()
pubKey = Base64.encodeToByte(pubkey.getEncoded())
priKey = Base64.encodeToByte(prikey.getEncoded())
System.out.println("pubKey = " + new String(pubKey))
System.out.println("priKey = " + new String(priKey))
} catch (java.lang.Exception e) {
System.out.println("生成密钥对失败")
e.printStackTrace()
}
}
public byte[] getPriKey() {
return priKey
}
public byte[] getPubKey() {
return pubKey
}
}
public class Signaturer {
/**
*
* Description:数字签名
*
* @param priKeyText
* @param plainText
* @return
* @author 孙钰佳
* @since:2007-12-27 上午10:51:48
*/
public static byte[] sign(byte[] priKeyText, String plainText) {
try {
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64
.decode(priKeyText))
KeyFactory keyf = KeyFactory.getInstance("RSA")
PrivateKey prikey = keyf.generatePrivate(priPKCS8)
// 用私钥对信息生成数字签名
java.security.Signature signet = java.security.Signature
.getInstance("MD5withRSA")
signet.initSign(prikey)
signet.update(plainText.getBytes())
byte[] signed = Base64.encodeToByte(signet.sign())
return signed
} catch (java.lang.Exception e) {
System.out.println("签名失败")
e.printStackTrace()
}
return null
}
}
public class SignProvider {
private SignProvider() {
}
/**
*
* Description:校验数字签名,此方法不会抛出任务异常,成功返回true,失败返回false,要求全部参数不能为空
*
* @param pubKeyText
*公钥,base64编码念闭
* @param plainText
*明文
* @param signTest
*数字签名的密文,base64编码
* @return 校验成功返回true 失败返回false
* @author 孙钰佳
* @since:2007-12-27 上午09:33:55
*/
public static boolean verify(byte[] pubKeyText, String plainText,
byte[] signText) {
try {
// 解密由base64编码的公钥,并构造X509EncodedKeySpec对象
java.security.spec.X509EncodedKeySpec bobPubKeySpec = new java.security.spec.X509EncodedKeySpec(
Base64.decode(pubKeyText))
// RSA对称加密算法
java.security.KeyFactory keyFactory = java.security.KeyFactory
.getInstance("RSA")
// 取公钥匙对象
java.security.PublicKey pubKey = keyFactory
.generatePublic(bobPubKeySpec)
// 解密由base64编码的数字签名
byte[] signed = Base64.decode(signText)
java.security.Signature signatureChecker = java.security.Signature
.getInstance("MD5withRSA")
signatureChecker.initVerify(pubKey)
signatureChecker.update(plainText.getBytes())
// 验证签名是否正常
if (signatureChecker.verify(signed))
return true
else
return false
} catch (Throwable e) {
System.out.println("校验签名失败")
e.printStackTrace()
return false
}
}
}
望采纳,谢谢。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)