RSA演算法加密本來就是很慢的。一般對某個文件加密的話用DES演算法加密,然後對密鑰用RSA演算法加密。RSA加密慢的問題目前無法解決;
Ⅱ java加密問題,RSA演算法
無法找到文件異常。樓主確定路徑正確。後綴名正確
FileInputStream f=new FileInputStream("Skey_RSA_pub.dat");
樓主你的文件放在什麼位置
Ⅲ 求RSA演算法JAVA實現源代碼(帶界面的)
import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.RSAPublicKeySpec;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.InvalidKeySpecException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.io.*;
import java.math.BigInteger;
/**
* RSA 工具類。提供加密,解密,生成密鑰對等方法。
* 需要到http://www.bouncycastle.org下載bcprov-jdk14-123.jar。
* @author xiaoyusong
* mail: [email protected]
* msn:[email protected]
* @since 2004-5-20
*
*/
public class RSAUtil {
/**
* 生成密鑰對
* @return KeyPair
* @throws EncryptException
*/
public static KeyPair generateKeyPair() throws EncryptException {
try {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA",
new org.bouncycastle.jce.provider.BouncyCastleProvider());
final int KEY_SIZE = 1024;//沒什麼好說的了,這個值關繫到塊加密的大小,可以更改,但是不要太大,否則效率會低
keyPairGen.initialize(KEY_SIZE, new SecureRandom());
KeyPair keyPair = keyPairGen.genKeyPair();
return keyPair;
} catch (Exception e) {
throw new EncryptException(e.getMessage());
}
}
/**
* 生成公鑰
* @param molus
* @param publicExponent
* @return RSAPublicKey
* @throws EncryptException
*/
public static RSAPublicKey generateRSAPublicKey(byte[] molus, byte[] publicExponent) throws EncryptException {
KeyFactory keyFac = null;
try {
keyFac = KeyFactory.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
} catch (NoSuchAlgorithmException ex) {
throw new EncryptException(ex.getMessage());
}
RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(molus), new BigInteger(publicExponent));
try {
return (RSAPublicKey) keyFac.generatePublic(pubKeySpec);
} catch (InvalidKeySpecException ex) {
throw new EncryptException(ex.getMessage());
}
}
/**
* 生成私鑰
* @param molus
* @param privateExponent
* @return RSAPrivateKey
* @throws EncryptException
*/
public static RSAPrivateKey generateRSAPrivateKey(byte[] molus, byte[] privateExponent) throws EncryptException {
KeyFactory keyFac = null;
try {
keyFac = KeyFactory.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
} catch (NoSuchAlgorithmException ex) {
throw new EncryptException(ex.getMessage());
}
RSAPrivateKeySpec priKeySpec = new RSAPrivateKeySpec(new BigInteger(molus), new BigInteger(privateExponent));
try {
return (RSAPrivateKey) keyFac.generatePrivate(priKeySpec);
} catch (InvalidKeySpecException ex) {
throw new EncryptException(ex.getMessage());
}
}
/**
* 加密
* @param key 加密的密鑰
* @param data 待加密的明文數據
* @return 加密後的數據
* @throws EncryptException
*/
public static byte[] encrypt(Key key, byte[] data) throws EncryptException {
try {
Cipher cipher = Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
cipher.init(Cipher.ENCRYPT_MODE, key);
int blockSize = cipher.getBlockSize();//獲得加密塊大小,如:加密前數據為128個byte,而key_size=1024 加密塊大小為127 byte,加密後為128個byte;因此共有2個加密塊,第一個127 byte第二個為1個byte
int outputSize = cipher.getOutputSize(data.length);//獲得加密塊加密後塊大小
int leavedSize = data.length % blockSize;
int blocksSize = leavedSize != 0 ? data.length / blockSize + 1 : data.length / blockSize;
byte[] raw = new byte[outputSize * blocksSize];
int i = 0;
while (data.length - i * blockSize > 0) {
if (data.length - i * blockSize > blockSize)
cipher.doFinal(data, i * blockSize, blockSize, raw, i * outputSize);
else
cipher.doFinal(data, i * blockSize, data.length - i * blockSize, raw, i * outputSize);
//這裡面doUpdate方法不可用,查看源代碼後發現每次doUpdate後並沒有什麼實際動作除了把byte[]放到ByteArrayOutputStream中,而最後doFinal的時候才將所有的byte[]進行加密,可是到了此時加密塊大小很可能已經超出了OutputSize所以只好用dofinal方法。
i++;
}
return raw;
} catch (Exception e) {
throw new EncryptException(e.getMessage());
}
}
/**
* 解密
* @param key 解密的密鑰
* @param raw 已經加密的數據
* @return 解密後的明文
* @throws EncryptException
*/
public static byte[] decrypt(Key key, byte[] raw) throws EncryptException {
try {
Cipher cipher = Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
cipher.init(cipher.DECRYPT_MODE, key);
int blockSize = cipher.getBlockSize();
ByteArrayOutputStream bout = new ByteArrayOutputStream(64);
int j = 0;
while (raw.length - j * blockSize > 0) {
bout.write(cipher.doFinal(raw, j * blockSize, blockSize));
j++;
}
return bout.toByteArray();
} catch (Exception e) {
throw new EncryptException(e.getMessage());
}
}
/**
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
File file = new File("test.html");
FileInputStream in = new FileInputStream(file);
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] tmpbuf = new byte[1024];
int count = 0;
while ((count = in.read(tmpbuf)) != -1) {
bout.write(tmpbuf, 0, count);
tmpbuf = new byte[1024];
}
in.close();
byte[] orgData = bout.toByteArray();
KeyPair keyPair = RSAUtil.generateKeyPair();
RSAPublicKey pubKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey priKey = (RSAPrivateKey) keyPair.getPrivate();
byte[] pubModBytes = pubKey.getMolus().toByteArray();
byte[] pubPubExpBytes = pubKey.getPublicExponent().toByteArray();
byte[] priModBytes = priKey.getMolus().toByteArray();
byte[] priPriExpBytes = priKey.getPrivateExponent().toByteArray();
RSAPublicKey recoveryPubKey = RSAUtil.generateRSAPublicKey(pubModBytes,pubPubExpBytes);
RSAPrivateKey recoveryPriKey = RSAUtil.generateRSAPrivateKey(priModBytes,priPriExpBytes);
byte[] raw = RSAUtil.encrypt(priKey, orgData);
file = new File("encrypt_result.dat");
OutputStream out = new FileOutputStream(file);
out.write(raw);
out.close();
byte[] data = RSAUtil.decrypt(recoveryPubKey, raw);
file = new File("decrypt_result.html");
out = new FileOutputStream(file);
out.write(data);
out.flush();
out.close();
}
}
http://book.77169.org/data/web5409/20050328/20050328__3830259.html
這個行吧
http://soft.zdnet.com.cn/software_zone/2007/0925/523319.shtml
再參考這個吧
http://topic.csdn.net/t/20040427/20/3014655.html
Ⅳ RSA PKCS#1在java中怎麼實現
樓主看看下面的代碼是不是你所需要的,這是我原來用的時候收集的
import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.RSAPublicKeySpec;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.InvalidKeySpecException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.io.*;
import java.math.BigInteger;
/**
* RSA 工具類。提供加密,解密,生成密鑰對等方法。
* 需要到http://www.bouncycastle.org下載bcprov-jdk14-123.jar。
* RSA加密原理概述
* RSA的安全性依賴於大數的分解,公鑰和私鑰都是兩個大素數(大於100的十進制位)的函數。
* 據猜測,從一個密鑰和密文推斷出明文的難度等同於分解兩個大素數的積
* ===================================================================
* (該演算法的安全性未得到理論的證明)
* ===================================================================
* 密鑰的產生:
* 1.選擇兩個大素數 p,q ,計算 n=p*q;
* 2.隨機選擇加密密鑰 e ,要求 e 和 (p-1)*(q-1)互質
* 3.利用 Euclid 演算法計算解密密鑰 d , 使其滿足 e*d = 1(mod(p-1)*(q-1)) (其中 n,d 也要互質)
* 4:至此得出公鑰為 (n,e) 私鑰為 (n,d)
* ===================================================================
* 加解密方法:
* 1.首先將要加密的信息 m(二進製表示) 分成等長的數據塊 m1,m2,...,mi 塊長 s(盡可能大) ,其中 2^s<n
* 2:對應的密文是: ci = mi^e(mod n)
* 3:解密時作如下計算: mi = ci^d(mod n)
* ===================================================================
* RSA速度
* 由於進行的都是大數計算,使得RSA最快的情況也比DES慢上100倍,無論是軟體還是硬體實現。
* 速度一直是RSA的缺陷。一般來說只用於少量數據加密。
* 文件名:RSAUtil.java<br>
* @author 趙峰<br>
* 版本:1.0.1<br>
* 描述:本演算法摘自網路,是對RSA演算法的實現<br>
* 創建時間:2009-7-10 下午09:58:16<br>
* 文件描述:首先生成兩個大素數,然後根據Euclid演算法生成解密密鑰<br>
*/
public class RSAUtil {
//密鑰對
private KeyPair keyPair = null;
/**
* 初始化密鑰對
*/
public RSAUtil(){
try {
this.keyPair = this.generateKeyPair();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 生成密鑰對
* @return KeyPair
* @throws Exception
*/
private KeyPair generateKeyPair() throws Exception {
try {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA",new org.bouncycastle.jce.provider.BouncyCastleProvider());
//這個值關繫到塊加密的大小,可以更改,但是不要太大,否則效率會低
final int KEY_SIZE = 1024;
keyPairGen.initialize(KEY_SIZE, new SecureRandom());
KeyPair keyPair = keyPairGen.genKeyPair();
return keyPair;
} catch (Exception e) {
throw new Exception(e.getMessage());
}
}
/**
* 生成公鑰
* @param molus
* @param publicExponent
* @return RSAPublicKey
* @throws Exception
*/
private RSAPublicKey generateRSAPublicKey(byte[] molus, byte[] publicExponent) throws Exception {
KeyFactory keyFac = null;
try {
keyFac = KeyFactory.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
} catch (NoSuchAlgorithmException ex) {
throw new Exception(ex.getMessage());
}
RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(molus), new BigInteger(publicExponent));
try {
return (RSAPublicKey) keyFac.generatePublic(pubKeySpec);
} catch (InvalidKeySpecException ex) {
throw new Exception(ex.getMessage());
}
}
/**
* 生成私鑰
* @param molus
* @param privateExponent
* @return RSAPrivateKey
* @throws Exception
*/
private RSAPrivateKey generateRSAPrivateKey(byte[] molus, byte[] privateExponent) throws Exception {
KeyFactory keyFac = null;
try {
keyFac = KeyFactory.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
} catch (NoSuchAlgorithmException ex) {
throw new Exception(ex.getMessage());
}
RSAPrivateKeySpec priKeySpec = new RSAPrivateKeySpec(new BigInteger(molus), new BigInteger(privateExponent));
try {
return (RSAPrivateKey) keyFac.generatePrivate(priKeySpec);
} catch (InvalidKeySpecException ex) {
throw new Exception(ex.getMessage());
}
}
/**
* 加密
* @param key 加密的密鑰
* @param data 待加密的明文數據
* @return 加密後的數據
* @throws Exception
*/
public byte[] encrypt(Key key, byte[] data) throws Exception {
try {
Cipher cipher = Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
cipher.init(Cipher.ENCRYPT_MODE, key);
// 獲得加密塊大小,如:加密前數據為128個byte,而key_size=1024 加密塊大小為127 byte,加密後為128個byte;
// 因此共有2個加密塊,第一個127 byte第二個為1個byte
int blockSize = cipher.getBlockSize();
// System.out.println("blockSize:"+blockSize);
int outputSize = cipher.getOutputSize(data.length);// 獲得加密塊加密後塊大小
// System.out.println("加密塊大小:"+outputSize);
int leavedSize = data.length % blockSize;
// System.out.println("leavedSize:"+leavedSize);
int blocksSize = leavedSize != 0 ? data.length / blockSize + 1 : data.length / blockSize;
byte[] raw = new byte[outputSize * blocksSize];
int i = 0;
while (data.length - i * blockSize > 0) {
if (data.length - i * blockSize > blockSize)
cipher.doFinal(data, i * blockSize, blockSize, raw, i * outputSize);
else
cipher.doFinal(data, i * blockSize, data.length - i * blockSize, raw, i * outputSize);
// 這裡面doUpdate方法不可用,查看源代碼後發現每次doUpdate後並沒有什麼實際動作除了把byte[]放到ByteArrayOutputStream中
// 而最後doFinal的時候才將所有的byte[]進行加密,可是到了此時加密塊大小很可能已經超出了OutputSize所以只好用dofinal方法。
i++;
}
return raw;
} catch (Exception e) {
throw new Exception(e.getMessage());
}
}
/**
* 解密
* @param key 解密的密鑰
* @param raw 已經加密的數據
* @return 解密後的明文
* @throws Exception
*/
@SuppressWarnings("static-access")
public byte[] decrypt(Key key, byte[] raw) throws Exception {
try {
Cipher cipher = Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
cipher.init(cipher.DECRYPT_MODE, key);
int blockSize = cipher.getBlockSize();
ByteArrayOutputStream bout = new ByteArrayOutputStream(64);
int j = 0;
while (raw.length - j * blockSize > 0) {
bout.write(cipher.doFinal(raw, j * blockSize, blockSize));
j++;
}
return bout.toByteArray();
} catch (Exception e) {
throw new Exception(e.getMessage());
}
}
/**
* 返回公鑰
* @return
* @throws Exception
*/
public RSAPublicKey getRSAPublicKey() throws Exception{
//獲取公鑰
RSAPublicKey pubKey = (RSAPublicKey) keyPair.getPublic();
//獲取公鑰系數(位元組數組形式)
byte[] pubModBytes = pubKey.getMolus().toByteArray();
//返回公鑰公用指數(位元組數組形式)
byte[] pubPubExpBytes = pubKey.getPublicExponent().toByteArray();
//生成公鑰
RSAPublicKey recoveryPubKey = this.generateRSAPublicKey(pubModBytes,pubPubExpBytes);
return recoveryPubKey;
}
/**
* 獲取私鑰
* @return
* @throws Exception
*/
public RSAPrivateKey getRSAPrivateKey() throws Exception{
// 獲取私鑰
RSAPrivateKey priKey = (RSAPrivateKey) keyPair.getPrivate();
// 返回私鑰系數(位元組數組形式)
byte[] priModBytes = priKey.getMolus().toByteArray();
// 返回私鑰專用指數(位元組數組形式)
byte[] priPriExpBytes = priKey.getPrivateExponent().toByteArray();
// 生成私鑰
RSAPrivateKey recoveryPriKey = this.generateRSAPrivateKey(priModBytes,priPriExpBytes);
return recoveryPriKey;
}
/**
* 測試
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
RSAUtil rsa = new RSAUtil();
String str = "天龍八部、神鵰俠侶、射鵰英雄傳白馬嘯西風";
RSAPublicKey pubKey = rsa.getRSAPublicKey();
RSAPrivateKey priKey = rsa.getRSAPrivateKey();
// System.out.println("加密後==" + new String(rsa.encrypt(pubKey,str.getBytes())));
String mw = new String(rsa.encrypt(pubKey, str.getBytes()));
System.out.println("加密後:"+mw);
// System.out.println("解密後:");
System.out.println("解密後==" + new String(rsa.decrypt(priKey,rsa.encrypt(pubKey,str.getBytes()))));
}
}
Ⅳ 基於java的rsa對文件加密。java寫的後台
一定要把邏輯寫進jsp嗎?如果是,可以把你的java類import進jsp,然後直接在jsp的<%%>里new一個調用就行。比如<%MyClass myClass = new MyClass(); String encData = myClass.rsaEncrypt(myData);%>
Ⅵ Java環境下有沒有辦法加速RSA加解密的速度
android和java webservice RSA處理的不同 1.andorid機器上生成的(密鑰對由伺服器在windows xp下生成並將公鑰發給客戶端保存)密碼無法在伺服器通過私鑰解密。 2.為了測試,在伺服器本地加解密正常,另外,在android上加解密也正常,但是在伺服器中加密(使用相同公鑰)後的密碼同樣無法在android系統解密(使用相同私鑰)。 3.由於對RSA加密演算法不了解,而且對Java RSA的加密過程也不清楚、谷歌一番,才了解到可能是加密過程中的填充字元長度不同,這跟加解密時指定的RSA演算法有關系。 4. 比如,在A機中使用標准RSA通過公鑰加密,然後在B系統中使用「RSA/ECB/NoPadding」使用私鑰解密,結果可以解密,但是會發現解密後的原文前面帶有很多特殊字元,這就是在加密前填充的空字元;如果在B系統中仍然使用標準的RSA演算法解密,這在相同類型的JDK虛擬機環境下當然是完全一樣的,關鍵是android系統使用的虛擬機(dalvik)跟SUN標准JDK是有所區別的,其中他們默認的RSA實現就不同。 5.更形象一點,在加密的時候加密的原文「abc」,直接使用「abc」.getBytes()方法獲得的bytes長度可能只有3,但是系統卻先把它放到一個512位的byte數組里,new byte[512],再進行加密。但是解密的時候使用的是「加密後的密碼」.getBytes()來解密,解密後的原文自然就是512長度的數據,即是在「abc」之外另外填充了500多位元組的其他空字元。
Ⅶ Java中RSA的方式如何實現非對稱加密的示例
代碼如下,需要依賴一個jar包commons-codec-1.9.jar,用於Base64轉換,請自行下載。
importorg.apache.commons.codec.binary.Base64;
importjavax.crypto.BadPaddingException;
importjavax.crypto.Cipher;
importjavax.crypto.IllegalBlockSizeException;
importjava.io.ByteArrayOutputStream;
importjava.io.UnsupportedEncodingException;
importjava.security.*;
importjava.security.interfaces.RSAPrivateKey;
importjava.security.interfaces.RSAPublicKey;
importjava.security.spec.PKCS8EncodedKeySpec;
importjava.security.spec.X509EncodedKeySpec;
publicclassRSAUtils{
//加密方式
="RSA";
//簽名演算法
_ALGORITHM="SHA1WithRSA";
//創建密鑰對初始長度
privatestaticfinalintKEY_SIZE=512;
//字元編碼格式
="UTF-8";
//RSA最大加密明文大小
privatestaticfinalintMAX_ENCRYPT_BLOCK=117;
//RSA最大解密密文大小
privatestaticfinalintMAX_DECRYPT_BLOCK=128;
privateKeyFactorykeyFactory;
publicRSAUtils(){
keyFactory=KeyFactory.getInstance(ALGORITHM);
}
/**
*私鑰加密
*
*@paramcontent待加密字元串
*@paramprivateKey私鑰
*@return加密後字元串(BASE64編碼)
*/
(Stringcontent,StringprivateKey)throwsException{
Stringresult;
try(ByteArrayOutputStreamout=newByteArrayOutputStream()){
byte[]keyBytes=newBase64().decode(privateKey);
=newPKCS8EncodedKeySpec(keyBytes);
PrivateKeypKey=keyFactory.generatePrivate(pkcs8KeySpec);
Ciphercipher=Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE,pKey);
byte[]data=content.getBytes(CHARSET);
write2Stream(cipher,data,out);
byte[]resultBytes=out.toByteArray();
result=Base64.encodeBase64String(resultBytes);
}catch(Exceptione){
thrownewException(e);
}
returnresult;
}
/**
*公鑰解密
*
*@paramcontent已加密字元串(BASE64加密)
*@parampublicKey公鑰
*@return
*/
(Stringcontent,StringpublicKey)throwsException{
Stringresult="";
try(ByteArrayOutputStreamout=newByteArrayOutputStream()){
byte[]keyBytes=newBase64().decode(publicKey);
X509EncodedKeySpecx509KeySpec=newX509EncodedKeySpec(keyBytes);
PublicKeypKey=keyFactory.generatePublic(x509KeySpec);
Ciphercipher=Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE,pKey);
byte[]data=Base64.decodeBase64(content);
write2Stream(cipher,data,out);
byte[]resultBytes=out.toByteArray();
result=newString(resultBytes);
}catch(Exceptione){
thrownewException(e);
}
returnresult;
}
/**
*公鑰加密
*
*@paramcontent待加密字元串
*@parampublicKey公鑰
*@return加密後字元串(BASE64編碼)
*/
(Stringcontent,StringpublicKey)throwsException{
Stringresult="";
try(ByteArrayOutputStreamout=newByteArrayOutputStream()){
byte[]keyBytes=newBase64().decode(publicKey);
X509EncodedKeySpecx509KeySpec=newX509EncodedKeySpec(keyBytes);
PublicKeypKey=keyFactory.generatePublic(x509KeySpec);
Ciphercipher=Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE,pKey);
byte[]data=content.getBytes(CHARSET);
write2Stream(cipher,
data,out);
byte[]resultBytes=out.toByteArray();
result=Base64.encodeBase64String(resultBytes);
}catch(Exceptione){
thrownewException(e);
}
returnresult;
}
/**
*私鑰解密
*
*@paramcontent已加密字元串
*@paramprivateKey私鑰
*@return解密後字元串
*/
(Stringcontent,StringprivateKey)throwsException{
Stringresult="";
try(ByteArrayOutputStreamout=newByteArrayOutputStream()){
byte[]keyBytes=newBase64().decode(privateKey);
=newPKCS8EncodedKeySpec(keyBytes);
PrivateKeypKey=keyFactory.generatePrivate(pkcs8KeySpec);
Ciphercipher=Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE,pKey);
byte[]data=Base64.decodeBase64(content);
write2Stream(cipher,data,out);
byte[]resultBytes=out.toByteArray();
result=newString(resultBytes);
}catch(Exceptione){
thrownewException(e);
}
returnresult;
}
privatestaticvoidwrite2Stream(Ciphercipher,byte[]data,ByteArrayOutputStreamout)throws
BadPaddingException,IllegalBlockSizeException{
intdataLen=data.length;
intoffSet=0;
byte[]cache;
inti=0;
//對數據分段解密
while(dataLen-offSet>0){
if(dataLen-offSet>MAX_DECRYPT_BLOCK){
cache=cipher.doFinal(data,offSet,MAX_DECRYPT_BLOCK);
}else{
cache=cipher.doFinal(data,offSet,dataLen-offSet);
}
out.write(cache,0,cache.length);
i++;
offSet=i*MAX_DECRYPT_BLOCK;
}
}
/**
*用私鑰對信息生成數字簽名
*
*@paramdata已加密數據
*@paramprivateKey私鑰(BASE64編碼)
*@returnsign
*/
publicStringsign(Stringdata,StringprivateKey)throwsException{
Stringresult="";
try{
byte[]keyBytes=newBase64().decode(privateKey);
=newPKCS8EncodedKeySpec(keyBytes);
PrivateKeyprivateK=keyFactory.generatePrivate(pkcs8KeySpec);
Signaturesignature=Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initSign(privateK);
signature.update(parse2HexStr(data).getBytes(CHARSET));
result=newBase64().encodeToString(signature.sign());
}catch(Exceptione){
thrownewException(e);
}
returnresult;
}
/**
*校驗數字簽名
*
*@paramdata已加密數據
*@parampublicKey公鑰(BASE64編碼)
*@paramsign數字簽名
*@return
*@throwsException
*/
publicbooleanverify(Stringdata,StringpublicKey,Stringsign)throwsException{
booleanresult;
try{
byte[]keyBytes=newBase64().decode(publicKey);
X509EncodedKeySpeckeySpec=newX509EncodedKeySpec(keyBytes);
PublicKeypublicK=keyFactory.generatePublic(keySpec);
Signaturesignature=Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initVerify(publicK);
signature.update(parse2HexStr(data).getBytes(CHARSET));
result=signature.verify(newBase64().decode(sign));
}catch(Exceptione){
thrownewException(e);
}
returnresult;
}
/**
*將二進制轉換成16進制
*
*@paramdata
*@return
*/
(Stringdata)throwsException{
Stringresult="";
try{
byte[]buf=data.getBytes(CHARSET);
StringBuffersb=newStringBuffer();
for(inti=0;i<buf.length;i++){
Stringhex=Integer.toHexString(buf[i]&0xFF);
if(hex.length()==1){
hex='0'+hex;
}
sb.append(hex.toUpperCase());
}
result=sb.toString();
}catch(UnsupportedEncodingExceptione){
thrownewException(e);
}
returnresult;
}
/**
*生成公鑰與私鑰
*/
publicstaticvoidcreateKey()throwsException{
try{
=KeyPairGenerator.getInstance(ALGORITHM);
keyPairGenerator.initialize(KEY_SIZE);
KeyPairkeyPair=keyPairGenerator.generateKeyPair();
RSAPublicKeyrsaPublicKey=(RSAPublicKey)keyPair.getPublic();
RSAPrivateKeyrsaPrivateKey=(RSAPrivateKey)keyPair.getPrivate();
StringpublicKey=Base64.encodeBase64String(rsaPublicKey.getEncoded());
StringprivateKey=Base64.encodeBase64String(rsaPrivateKey.getEncoded());
System.out.println("publicKey="+publicKey+" privateKey="+privateKey);
}catch(NoSuchAlgorithmExceptione){
thrownewException(e);
}
}
publicstaticvoidmain(String[]args)throwsException{
StringPRIVATE_KEY="+m+/fNs1bmgfJhI8lhr/o/Hy8EFB/I/DDyLcCcU4bCLtxpki8edC+KJR2WvyYfnVmWEe//++W5C+lesEOAqdO5nahRZsL8BIDoxTEn2j+DSa///1qX+t8f5wD8i/8GU702PeCwkGI5ymrARq+/+/nkefTq0SNpUDVbGxVpJi9/FOUf";
StringPUBLIC_KEY="+lc///NfOvKvQndzDH60DzLGOMdE0NBrTn/5zEjGwJbVdlvCfOiHwIDAQAB";
RSAUtilsrsaUtil=newRSAUtils();
StringencryptByPublicKey=rsaUtil.encryptByPublicKey("你好!",PUBLIC_KEY);
System.out.println(encryptByPublicKey);
StringdecryptByPrivateKey=rsaUtil.decryptByPrivateKey(encryptByPublicKey,PRIVATE_KEY);
System.out.println(decryptByPrivateKey);
StringencryptByPrivateKey=rsaUtil.encryptByPrivateKey("你好!",PRIVATE_KEY);
System.out.println(encryptByPrivateKey);
StringdecryptByPublicKey=rsaUtil.decryptByPublicKey(encryptByPrivateKey,PUBLIC_KEY);
System.out.println(decryptByPublicKey);
Stringsign=rsaUtil.sign("1234",PRIVATE_KEY);
System.out.println("sign:"+sign);
System.out.println(rsaUtil.verify("1234",PUBLIC_KEY,sign));
}
}
Ⅷ java 中的Cipher類RSA方式能不能用私鑰加密公鑰解密,完整解釋下
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(1024);
KeyPair key = keyGen.generateKeyPair();
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
//把第二個參數改為 key.getPrivate()
cipher.init(Cipher.ENCRYPT_MODE, key.getPublic());
byte[] cipherText = cipher.doFinal("Message".getBytes("UTF8"));
System.out.println(new String(cipherText, "UTF8"));
//把第二個參數改為key.getPublic()
cipher.init(Cipher.DECRYPT_MODE, key.getPrivate());
byte[] newPlainText = cipher.doFinal(cipherText);
System.out.println(new String(newPlainText, "UTF8"));
正常的用公鑰加密私鑰解密就是這個過程,如果按私鑰加密公鑰解密,只要按備注改2個參數就可以。
但是我要提醒樓主,你要公鑰解密,公鑰是公開的,相當於任何人都查到公鑰可以解密。
你是想做簽名是吧。
Ⅸ java RSA演算法實現256位密鑰怎麼做
【下載實例】本文介紹RSA2加密與解密,RSA2是RSA的加強版本,在密鑰長度上採用2048, RSA2比RSA更安全,更可靠, 本人的另一篇文章RSA已經發表,有想了解的可以點開下面的RSA文章