公鑰加密java
一個比較簡單的實現:一個三個類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;
}
}
}
望採納,謝謝。
② JAVA公鑰加密,私鑰解密,該怎麼解決
public abstract class RSACoder extends Coder {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";/*** 用私鑰對信息生成數字簽名* * @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));}/*** 解密<br>* 用私鑰解密* * @param data* @param key* @return* @throws Exception*/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[] 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(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.ENCRYPT_MODE, publicKey);return cipher.doFinal(data);}/*** 加密<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, Object> 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, Object> keyMap)throws Exception {Key key = (Key) keyMap.get(PUBLIC_KEY);return encryptBASE64(key.getEncoded());}/*** 初始化密鑰* * @return* @throws Exception*/public static Map<String, Object> initKey() throws Exception {KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);keyPairGen.initialize(1024);KeyPair keyPair = keyPairGen.generateKeyPair();// 公鑰RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();// 私鑰RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();Map<String, Object> keyMap = new HashMap<String, Object>(2);keyMap.put(PUBLIC_KEY, publicKey);keyMap.put(PRIVATE_KEY, privateKey);return keyMap;}}
③ JAVA公鑰加密,私鑰解密,該怎麼解決
RSA加密演算法,是世界上第一個非對稱加密演算法,也是數論的第一個實際應用。它的演算法如下:
1.找兩個非常大的質數p和q(通常p和q都有155十進制位或都有512十進制位)並計算n=pq,k=(p-1)(q-1)。
2.將明文編碼成整數M,保證M不小於0但是小於n。
3.任取一個整數e,保證e和k互質,而且e不小於0但是小於k。加密鑰匙(稱作公鑰)是(e, n)。
4.找到一個整數d,使得ed除以k的余數是1(只要e和n滿足上面條件,d肯定存在)。解密鑰匙(稱作密鑰)是(d, n)。
加密過程: 加密後的編碼C等於M的e次方除以n所得的余數。
解密過程: 解密後的編碼N等於C的d次方除以n所得的余數。
只要e、d和n滿足上面給定的條件。M等於N。
④ Java 第三方公鑰 RSA加密求助
下面是RSA加密代碼。
/**
* 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;
}
}
⑤ JAVA公鑰加密,私鑰解密,該怎麼解決
public abstract class RSACoder extends Coder {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";/*** 用私鑰對信息生成數字簽名* * @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));}/*** 解密<br>* 用私鑰解密* * @param data* @param key* @return* @throws Exception*/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[] 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(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.ENCRYPT_MODE, publicKey);return cipher.doFinal(data);}/*** 加密<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, Object> 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, Object> keyMap)throws Exception {Key key = (Key) keyMap.get(PUBLIC_KEY);return encryptBASE64(key.getEncoded());}/*** 初始化密鑰* * @return* @throws Exception*/public static Map<String, Object> initKey() throws Exception {KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);keyPairGen.initialize(1024);KeyPair keyPair = keyPairGen.generateKeyPair();// 公鑰RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();// 私鑰RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();Map<String, Object> keyMap = new HashMap<String, Object>(2);keyMap.put(PUBLIC_KEY, publicKey);keyMap.put(PRIVATE_KEY, privateKey);return keyMap;}}
⑥ JAVA公鑰加密,私鑰解密,該怎麼解決
可以使用Java中的RSA加解密,公私鑰就是非對稱的,公鑰加密,私鑰解密。也可以使用硬體加密鎖,一般都支持RSA等加密演算法,比如ROCKEY。
⑦ 新的java程序公鑰加密演算法有哪些
AES和RSA都是加密演算法 AES屬於對稱加密演算法 RSA屬於非對稱加密演算法,公鑰和私鑰不一致 MD5是一種校驗方式,用於保證文件的正確性,防止被植入木馬或病毒
⑧ JAVA公鑰加密,私鑰解密,該怎麼解決
1、默認 Java 中僅支持 128 位密鑰,當使用 256 位密鑰的時候,會報告密鑰長度錯誤 Invalid AES key length 你需要下載一個支持更長密鑰的包。這個包叫做 Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files 6 看一下你的 JRE 環境,將 JRE 環境中 lib\lib\security 中的同名包替換掉。
2、Base64 問題 // 編碼 String asB64 = new Base64().encodeToString("some string".getBytes("utf-8")); System.out.println(asB64); // 輸出為: c29tZSBzdHJpbmc= 解碼 // 解碼 byte[] asBytes = new Base64().getDecoder().decode("c29tZSBzdHJpbmc="); System.out.println(new String(asBytes, "utf-8")); // 輸出為: some string ...
⑨ JAVA公鑰加密,私鑰解密,該怎麼解決
RSA演算法,選取兩個互質數
如p:6和q:5(最大公約數為1)
求出乘積n=30,歐拉函數值((p - 1) * (q - 1)) eul =20
選出一個和eul互質且小於eul大於1的數,如 e = 19
通過擴展歐幾里得演算法求逆元 此處求出一個逆元 d = 39
逆元就是滿足公式 (e*d) % eul = 1的值(該公式可能有多個解,求出一個就行)
(n,e)組成公鑰,(n,d)組成私鑰
假定明文是一個數字m
計算 m的e次方模n 得到的余數就是密文 em
計算 em的d次方模n 得到的余數就是明文 m
因此可以使用公鑰加密byte數組,使用私鑰解密還原byte數組
byte數組組成了字元串、文件等
最後注意,要加密的明文二進制位數不能超過密鑰的二進制位數
⑩ JAVA公鑰加密,私鑰解密,該怎麼解決
public String encryptStringWithRSA(RSAPublicKey publicKey,
String str)
{
String key;
try
{
key =
encode(publicKey.getEncoded());
byte[] keyBytes =
decode(key);
X509EncodedKeySpec x509KeySpec = new
X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory =
KeyFactory.getInstance(RSA);
Key publicK =
keyFactory.generatePublic(x509KeySpec);
// 對數據加密
Cipher cipher =
Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE,
publicK);
byte[] data = str.getBytes();
int inputLen =
data.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int
offSet = 0;
byte[] cache;
int i = 0;
// 對數據分段加密
while (inputLen -
offSet > 0)
{
if (inputLen - offSet >
MAX_ENCRYPT_BLOCK)
{
cache = cipher.doFinal(data, offSet,
MAX_ENCRYPT_BLOCK);
} else
{
cache = cipher.doFinal(data, offSet,
inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet
= i * MAX_ENCRYPT_BLOCK;
}
byte[] encryptedData =
out.toByteArray();
out.close();
return
parseByte2HexStr(encryptedData);
} catch (Exception
e)
{
e.printStackTrace();
}
return ERROR;
}
public
String decryptStringWithRSA(RSAPrivateKey privateKey, String str)
{
if
(!str.equals(""))
{
String key;
try
{
key =
encode(privateKey.getEncoded());
byte[] keyBytes =
decode(key);
PKCS8EncodedKeySpec pkcs8KeySpec = new
PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory =
KeyFactory.getInstance(RSA);
Key privateK =
keyFactory.generatePrivate(pkcs8KeySpec);
Cipher cipher =
Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE,
privateK);
byte[] encryptedData = parseHexStr2Byte(str);
int inputLen =
encryptedData.length;
ByteArrayOutputStream out = new
ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
//
對數據分段解密
while (inputLen - offSet > 0)
{
if (inputLen - offSet >
MAX_DECRYPT_BLOCK)
{
cache = cipher.doFinal(encryptedData, offSet,
MAX_DECRYPT_BLOCK);
} else
{
cache = cipher.doFinal(encryptedData,
offSet, inputLen - offSet);
}
out.write(cache, 0,
cache.length);
i++;
offSet = i * MAX_DECRYPT_BLOCK;
}
byte[]
decryptedData = out.toByteArray();
out.close();
return new
String(decryptedData);
} catch (Exception
e)
{
e.printStackTrace();
}
} else
{
return
str;
}
return ERROR;
}收起