package com.security; import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;java
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;算法
/**安全
RSA 公鑰加密算法是1977年由Ron Rivest、Adi Shamirh和LenAdleman在(美國麻省理工學院)開發的。RSA取名來自開發他們三者的名字。 RSA是目前最有影響力的公鑰加密算法,它可以抵抗到目前爲止已知的全部密碼攻擊,已被ISO推薦爲公鑰數據加密標準。RSA算法基於一個十分簡單的數論事實: 將兩個大素數相乘十分容易,但那時想要對其乘積進行因式分解卻極其困難,所以能夠將乘積公開做爲加密密鑰。 */ public class RSA {加密
/**對象
加密 /
protected byte[] encrypt(RSAPublicKey publicKey,byte[] srcBytes) throws Exception{
if(publicKey!=null){
//Cipher負責完成加密或解密工做,基於RSA
Cipher cipher = Cipher.getInstance("RSA");
//根據公鑰,對Cipher對象進行初始化
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] resultBytes = cipher.doFinal(srcBytes);
return resultBytes;
}
return null;
}
/*ip
解密
/
protected byte[] decrypt(RSAPrivateKey privateKey,byte[] srcBytes) throws Exception{
if(privateKey!=null){
//Cipher負責完成加密或解密工做,基於RSA
Cipher cipher = Cipher.getInstance("RSA");
//根據公鑰,對Cipher對象進行初始化
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] resultBytes = cipher.doFinal(srcBytes);
return resultBytes;
}
return null;
}
/*ci
test */
public static void main(String[] args) throws Exception {
RSA rsa = new RSA();
String msg = "張三是好人";
//KeyPairGenerator類用於生成公鑰和私鑰對,基於RSA算法生成對象
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
//初始化密鑰對生成器,密鑰大小爲1024位
keyPairGen.initialize(1024);
//生成一個密鑰對,保存在keyPair中
KeyPair keyPair = keyPairGen.generateKeyPair();
//獲得私鑰
RSAPrivateKey privateKey = (RSAPrivateKey)keyPair.getPrivate();
//獲得公鑰
RSAPublicKey publicKey = (RSAPublicKey)keyPair.getPublic();開發
//用公鑰加密
byte[] srcBytes = msg.getBytes();
byte[] resultBytes = rsa.encrypt(publicKey, srcBytes);get
//用私鑰解密
byte[] decBytes = rsa.decrypt(privateKey, resultBytes);it
System.out.println("明文是:" + msg);
System.out.println("加密後是:" + new String(resultBytes));
System.out.println("解密後是:" + new String(decBytes));
}
}