91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

java加解密RSA使用方法代碼示例

發布時間:2020-10-10 14:32:48 來源:腳本之家 閱讀:260 作者:拍碼屁 欄目:編程語言

最近為了分析一段請求流,不得不去研究一下RSA加密。

首先,強調一點:密鑰的“鑰”讀“yue”,不是“yao”,額。。。

網上關于RSA的原理一抓一大把的,這里只是簡單說說我的理解:

1. 兩個足夠大的互質數p, q;
2. 用于模運算的模 n=p*q;
3. 公鑰KU(e, n)中的e滿足 1<e< (p-1)(q-1),且與(p-1)(q-1)互質;
4. 密鑰KR(d, n)中的d滿足  d*e % (p-1)(q-1)= 1,%是取余運算。

因為公鑰是公開的,所以我知道了e和n,那么根據2,3,4式子的關系,我們只要從n的值推出p, q的值則可計算出d的值,也就能找到密鑰。

然而,關鍵就在這里, n=p*q,如果兩個互質數p和q足夠大,那么根據目前的計算機技術和其他工具,至今也沒能從n分解出p和q,這是數學上的一個難題,也正是這個難題成為了RSA加密至今被廣泛使用的原因。換句話說,只要密鑰長度n足夠大(一般1024足矣),基本上不可能從公鑰信息推出私鑰信息。

好了,這里作為研究的隨筆,記錄一下java如何使用,以下主要有三種方法,基本大同小異,只是獲取公鑰私鑰的途徑不一樣就是了:

方法一:

利用KeyPairGenerator直接生成公鑰和密鑰,一般私鑰保留給服務端,公鑰交給客戶端。

public class RSACryptography {
	public static String data="hello world";
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		KeyPair keyPair=genKeyPair(1024);
		//獲取公鑰,并以base64格式打印出來
		PublicKey publicKey=keyPair.getPublic();		
		System.out.println("公鑰:"+new String(Base64.getEncoder().encode(publicKey.getEncoded())));
		//獲取私鑰,并以base64格式打印出來
		PrivateKey privateKey=keyPair.getPrivate();		
		System.out.println("私鑰:"+new String(Base64.getEncoder().encode(privateKey.getEncoded())));
		//公鑰加密
		byte[] encryptedBytes=encrypt(data.getBytes(), publicKey);	
		System.out.println("加密后:"+new String(encryptedBytes));
		//私鑰解密
		byte[] decryptedBytes=decrypt(encryptedBytes, privateKey);		
		System.out.println("解密后:"+new String(decryptedBytes));
	}
	//生成密鑰對
	public static KeyPair genKeyPair(int keyLength) throws Exception{
		KeyPairGenerator keyPairGenerator=KeyPairGenerator.getInstance("RSA");
		keyPairGenerator.initialize(1024);		
		return keyPairGenerator.generateKeyPair();
	}
	//公鑰加密
	public static byte[] encrypt(byte[] content, PublicKey publicKey) throws Exception{
		Cipher cipher=Cipher.getInstance("RSA");//java默認"RSA"="RSA/ECB/PKCS1Padding"
		cipher.init(Cipher.ENCRYPT_MODE, publicKey);
		return cipher.doFinal(content);
	}
	//私鑰解密
	public static byte[] decrypt(byte[] content, PrivateKey privateKey) throws Exception{
		Cipher cipher=Cipher.getInstance("RSA");
		cipher.init(Cipher.DECRYPT_MODE, privateKey);
		return cipher.doFinal(content);
	}
}

運行結果:

公鑰:MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCSl6V7XNkVR9+NotekZm1FjHdL7oDqA66hrG5D/wgQ1XIF22mex7pnNc8PRBRScJQZJbzQ3ZnVmV5XqrVSCGbqaMPFmIXetu6lifQHoGptH9ghZsemanqp0sSd1TkHcPL2Njk/hZabWYBzPbjlidgfcMotehnFUdlIMGCusMV0awIDAQAB
私鑰:MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAJKXpXtc2RVH342i16RmbUWMd0vugOoDrqGsbkP/CBDVcgXbaZ7Humc1zw9EFFJwlBklvNDdmdWZXleqtVIIZupow8WYhd627qWJ9Aegam0f2CFmx6ZqeqnSxJ3VOQdw8vY2OT+FlptZgHM9uOWJ2B9wyi16GcVR2UgwYK6wxXRrAgMBAAECgYA8YBjX5jXCfgek3hzSqRz4OBIqQ+D0gO+7xrjjaHZ5+G8t2mB19Ozg9ViCgRednKBiexh6LcveHXytvrFPSAaagoa9DFKktaQmIQ15z3xXtgiHxg2dxDFJ1GNyhNjhMl8RSff2nSfQaRrgA8y36k0OZq240sdls6GbBMMoHRuRAQJBAOm6fw7cVXfmvzL0JBZmDl3SPK3sSNM6tfxaDy39W1g9rmGHKqs2XOubCe06ic/m9pxJnPmUXhgvYtiYLdC6NbkCQQCgj5O/sA0wYQQvW+WxQvleBLND9ZT2QOG5wvYRMoKP+uYE3SwsfKTZ1YsD5DjoyQPrc/lbCX7x+A8qRqLdRw1DAkAmhwJ4vaMtD5FG4e2s74fAuW4dMUzT3OKwxVupNhE/m3NKSlCjRmPMxpK9Ux/ycF0IaC4DCgz0qaL+lx8+P+OpAkA6Kol+AgtlIWBgv8wAYaDxPIas8gTbCTo9D7IRHNlLy7sUvANKwoT+HWxVJpKvUlNHMyZ8on4IrrLfv+M0go79AkAUwV5Nipi7ekScrzEMiaRJoYXgpFv2pQnRQzBQm5xVxtbuCpmuopNyk/9zm33RiwwjN6uYV9Hfg7e6HNsK2qIR
加密后:v?,Y9?檂o庬鉤h﹎m_?$惇櫤?p崍?4蹥bhhN?25/?6T駩樁w草遏鬼碙&柀&*軄Q晛1鱋A祉@眽`剪啃`噾?>x/運婣?HI砛奊瑘i?$B撈
?毟"ST
解密后:hello world

方法二:

實際上,方法一只是用來生成密鑰就OK了,生成的密鑰需要保存到本地文件中,所以一般不會在客戶端調用KeyPairGenerator進行密鑰的生成操作。

這里,我們可以將方法一得到的密鑰保存到文件,下次我們直接讀取就可以了。我假設以String的形式保存在文件內,那么接下來直接使用讀取到的String生成密鑰即可。

當然,你也可以使用openssl來生成也可以,不過我覺得麻煩就不弄了。

public class RSACryptography {
	public static String data="hello world";
	public static String publicKeyString="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCISLP98M/56HexX/9FDM8iuIEQozy6kn2JMcbZS5/BhJ+U4PZIChJfggYlWnd8NWn4BYr2kxxyO8Qgvc8rpRZCkN0OSLqLgZGmNvoSlDw80UXq90ZsVHDTOHuSFHw8Bv//B4evUNJBB8g9tpVxr6P5EJ6FMoR/kY2dVFQCQM4+5QIDAQAB";
	public static String privateKeyString="MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAIhIs/3wz/nod7Ff/0UMzyK4gRCjPLqSfYkxxtlLn8GEn5Tg9kgKEl+CBiVad3w1afgFivaTHHI7xCC9zyulFkKQ3Q5IuouBkaY2+hKUPDzRRer3RmxUcNM4e5IUfDwG//8Hh79Q0kEHyD22lXGvo/kQnoUyhH+RjZ1UVAJAzj7lAgMBAAECgYAVh36vsggY0Yl/Asw/qztZn837w93HF3cvYiaokxLErl/LVBJz5OtsHQ09f2IaxBFedfmy5CB9R0W/aly851JxrI8WAkx2W2FNllzhha01fmlNlOSumoiRF++JcbsAjDcrcIiR8eSVNuB6ymBCrx/FqhdX3+t/VUbSAFXYT9tsgQJBALsHurnovZS1qjCTl6pkNS0V5qio88SzYP7lzgq0eYGlvfupdlLX8/MrSdi4DherMTcutUcaTzgQU20uAI0EMyECQQC6il1Kdkw8Peeb0JZMHbs+cMCsbGATiAt4pfo1b/i9/BO0QnRgDqYcjt3J9Ux22dPYbDpDtMjMRNrAKFb4BJdFAkBMrdWTZOVc88IL2mcC98SJcII5wdL3YSeyOZto7icmzUH/zLFzM5CTsLq8/HDiqVArNJ4jwZia/q6Fg6e8KO2hAkB0EK1VLF/ox7e5GkK533Hmuu8XGWN6I5bHnbYd06qYQyTbbtHMBrFSaY4UH91Qwd3u9gAWqoCZoGnfT/o03V5lAkBqq8jZd2lHifey+9cf1hsHD5WQbjJKPPIb57CK08hn7vUlX5ePJ02Q8AhdZKETaW+EsqJWpNgsu5wPqsy2UynO";
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		//獲取公鑰 
		PublicKey publicKey=getPublicKey(publicKeyString);
		//獲取私鑰 
		PrivateKey privateKey=getPrivateKey(privateKeyString);		
		//公鑰加密
		byte[] encryptedBytes=encrypt(data.getBytes(), publicKey);	
		System.out.println("加密后:"+new String(encryptedBytes));
		//私鑰解密
		byte[] decryptedBytes=decrypt(encryptedBytes, privateKey);		
		System.out.println("解密后:"+new String(decryptedBytes));
	}
	//將base64編碼后的公鑰字符串轉成PublicKey實例
	public static PublicKey getPublicKey(String publicKey) throws Exception{
		byte[ ] keyBytes=Base64.getDecoder().decode(publicKey.getBytes());
		X509EncodedKeySpec keySpec=new X509EncodedKeySpec(keyBytes);
		KeyFactory keyFactory=KeyFactory.getInstance("RSA");
		return keyFactory.generatePublic(keySpec);	
	}
	//將base64編碼后的私鑰字符串轉成PrivateKey實例
	public static PrivateKey getPrivateKey(String privateKey) throws Exception{
		byte[ ] keyBytes=Base64.getDecoder().decode(privateKey.getBytes());
		PKCS8EncodedKeySpec keySpec=new PKCS8EncodedKeySpec(keyBytes);
		KeyFactory keyFactory=KeyFactory.getInstance("RSA");
		return keyFactory.generatePrivate(keySpec);
	}
	//公鑰加密
	public static byte[] encrypt(byte[] content, PublicKey publicKey) throws Exception{
		Cipher cipher=Cipher.getInstance("RSA");//java默認"RSA"="RSA/ECB/PKCS1Padding"
		cipher.init(Cipher.ENCRYPT_MODE, publicKey);
		return cipher.doFinal(content);
	}
	//私鑰解密
	public static byte[] decrypt(byte[] content, PrivateKey privateKey) throws Exception{
		Cipher cipher=Cipher.getInstance("RSA");
		cipher.init(Cipher.DECRYPT_MODE, privateKey);
		return cipher.doFinal(content);
	}
}

運行結果

加密后:.a羫閍Q癭u鉵やAS祏@q??>?:sQ3?A_l'遙`t?6蔍NK%IC尊[鷹#枋リ礼?1i獙	l躕鋨仩?"糍>Ij弻腡諾晦5uDq積嬨璼ey冖U'輵\L〥%
解密后:hello world

方法三:

除了保存密鑰字符串之外,其他的做法一般是只保存 模n(modulus),公鑰和私鑰的e和d(exponent)。

其中,n, e, d可以這樣獲取到,獲取到后可以保存到本地文件中。

//獲取公鑰 
RSAPublicKey publicKey=(RSAPublicKey) getPublicKey(publicKeyString); 
BigInteger modulus1=publicKey.getModulus(); 
BigInteger exponent1=publicKey.getPublicExponent(); 
   
//獲取私鑰 
RSAPrivateKey privateKey=(RSAPrivateKey) getPrivateKey(privateKeyString);     
BigInteger modulus2=privateKey.getModulus(); 
BigInteger exponent2=privateKey..getPrivateExponent(); 

這里,假設我已經從文件中讀取到了modulus和exponent:

public class RSACryptography {
	public static String data="hello world";
	public static String modulusString="95701876885335270857822974167577168764621211406341574477817778908798408856077334510496515211568839843884498881589280440763139683446418982307428928523091367233376499779842840789220784202847513854967218444344438545354682865713417516385450114501727182277555013890267914809715178404671863643421619292274848317157";
	public static String publicExponentString="65537";
	public static String privateExponentString="15118200884902819158506511612629910252530988627643229329521452996670429328272100404155979400725883072214721713247384231857130859555987849975263007110480563992945828011871526769689381461965107692102011772019212674436519765580328720044447875477151172925640047963361834004267745612848169871802590337012858580097";
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub		
		//由n和e獲取公鑰
		PublicKey publicKey=getPublicKey(modulusString, publicExponentString);
		//由n和d獲取私鑰
		PrivateKey privateKey=getPrivateKey(modulusString, privateExponentString);
		//公鑰加密
		byte[] encryptedBytes=encrypt(data.getBytes(), publicKey);	
		System.out.println("加密后:"+new String(encryptedBytes));
		//私鑰解密
		byte[] decryptedBytes=decrypt(encryptedBytes, privateKey);		
		System.out.println("解密后:"+new String(decryptedBytes));
	}
	//將base64編碼后的公鑰字符串轉成PublicKey實例
	public static PublicKey getPublicKey(String modulusStr, String exponentStr) throws Exception{
		BigInteger modulus=new BigInteger(modulusStr);
		BigInteger exponent=new BigInteger(exponentStr);
		RSAPublicKeySpec publicKeySpec=new RSAPublicKeySpec(modulus, exponent);
		KeyFactory keyFactory=KeyFactory.getInstance("RSA");
		return keyFactory.generatePublic(publicKeySpec);
	}
	//將base64編碼后的私鑰字符串轉成PrivateKey實例
	public static PrivateKey getPrivateKey(String modulusStr, String exponentStr) throws Exception{
		BigInteger modulus=new BigInteger(modulusStr);
		BigInteger exponent=new BigInteger(exponentStr);
		RSAPrivateKeySpec privateKeySpec=new RSAPrivateKeySpec(modulus, exponent);
		KeyFactory keyFactory=KeyFactory.getInstance("RSA");
		return keyFactory.generatePrivate(privateKeySpec);
	}
	//公鑰加密
	public static byte[] encrypt(byte[] content, PublicKey publicKey) throws Exception{
		Cipher cipher=Cipher.getInstance("RSA");//java默認"RSA"="RSA/ECB/PKCS1Padding"
		cipher.init(Cipher.ENCRYPT_MODE, publicKey);
		return cipher.doFinal(content);
	}
	//私鑰解密
	public static byte[] decrypt(byte[] content, PrivateKey privateKey) throws Exception{
		Cipher cipher=Cipher.getInstance("RSA");
		cipher.init(Cipher.DECRYPT_MODE, privateKey);
		return cipher.doFinal(content);
	}
}

運行結果:

加密后:g[>X锽.+?"s謉q琾B?,\??戮隴⒑e*y浌X蜤??眲Z秔豨Wm麞衹靫〩2孲*?X?9賚埤腴暎?~_邊槻U☉疀群廥5z鈦?
媷Bdh}>i1運癑障a杽
解密后:hello world

這里三種方式總結起來也就是

1,.KeyPairGenerator獲取key;
2. String獲取key;
3. modulus和exponent獲取key。

--------------------后來,我發現,數據太長拋異常了,好吧---------------------------

然而,當加密的數據太長的時候則需要分組加密,不然數據過長會拋異常,如“Encryt data is too much”,或者“data length is longer than 127”等。

上面三個方法使用的key的n值(modulus)是1024bit的,也就是128byte,根據RSA加密規則,加密1 byte字節的數據,需要12 byte,即其他11byte可能用于記錄其他信息什么的,這里我就不清楚了,而1024bit長度的key則最多可以加密128-11=117byte的數據,所以,對于超過117byte的數據,我們需要以117byte為一組進行數據分割。

public class RSACryptography {
	public static String data="hello world";
	public static String modulusString="95701876885335270857822974167577168764621211406341574477817778908798408856077334510496515211568839843884498881589280440763139683446418982307428928523091367233376499779842840789220784202847513854967218444344438545354682865713417516385450114501727182277555013890267914809715178404671863643421619292274848317157";
	public static String publicExponentString="65537";
	public static String privateExponentString="15118200884902819158506511612629910252530988627643229329521452996670429328272100404155979400725883072214721713247384231857130859555987849975263007110480563992945828011871526769689381461965107692102011772019212674436519765580328720044447875477151172925640047963361834004267745612848169871802590337012858580097";
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub		
		//由n和e獲取公鑰
		PublicKey publicKey=getPublicKey(modulusString, publicExponentString);
		//由n和d獲取私鑰
		PrivateKey privateKey=getPrivateKey(modulusString, privateExponentString);
		//公鑰加密
		String encrypted=encrypt(data, publicKey);	
		System.out.println("加密后:"+encrypted);	
		//私鑰解密
		String decrypted=decrypt(encrypted, privateKey);		
		System.out.println("解密后:"+new String(decrypted));
	}
	//將base64編碼后的公鑰字符串轉成PublicKey實例
	public static PublicKey getPublicKey(String modulusStr, String exponentStr) throws Exception{
		BigInteger modulus=new BigInteger(modulusStr);
		BigInteger exponent=new BigInteger(exponentStr);
		RSAPublicKeySpec publicKeySpec=new RSAPublicKeySpec(modulus, exponent);
		KeyFactory keyFactory=KeyFactory.getInstance("RSA");
		return keyFactory.generatePublic(publicKeySpec);
	}
	//將base64編碼后的私鑰字符串轉成PrivateKey實例
	public static PrivateKey getPrivateKey(String modulusStr, String exponentStr) throws Exception{
		BigInteger modulus=new BigInteger(modulusStr);
		BigInteger exponent=new BigInteger(exponentStr);
		RSAPrivateKeySpec privateKeySpec=new RSAPrivateKeySpec(modulus, exponent);
		KeyFactory keyFactory=KeyFactory.getInstance("RSA");
		return keyFactory.generatePrivate(privateKeySpec);
	}
	//公鑰加密,并轉換成十六進制字符串打印出來
	public static String encrypt(String content, PublicKey publicKey) throws Exception{
		Cipher cipher=Cipher.getInstance("RSA");//java默認"RSA"="RSA/ECB/PKCS1Padding"
		cipher.init(Cipher.ENCRYPT_MODE, publicKey);
		int splitLength=((RSAPublicKey)publicKey).getModulus().bitLength()/8-11;
		byte[][] arrays=splitBytes(content.getBytes(), splitLength);
		StringBuffer sb=new StringBuffer();
		for(byte[] array : arrays){			
			sb.append(bytesToHexString(cipher.doFinal(array)));
		}
		return sb.toString();
	}
	//私鑰解密,并轉換成十六進制字符串打印出來
	public static String decrypt(String content, PrivateKey privateKey) throws Exception{
		Cipher cipher=Cipher.getInstance("RSA");
		cipher.init(Cipher.DECRYPT_MODE, privateKey);
		int splitLength=((RSAPrivateKey)privateKey).getModulus().bitLength()/8;
		byte[] contentBytes=hexString2Bytes(content);
		byte[][] arrays=splitBytes(contentBytes, splitLength);
		StringBuffer sb=new StringBuffer();
		for(byte[] array : arrays){	
			sb.append(new String(cipher.doFinal(array)));
		}
		return sb.toString();
	}
	//拆分byte數組
	public static byte[][] splitBytes(byte[] bytes, int splitLength){
		int x; //商,數據拆分的組數,余數不為0時+1
		int y; //余數
		y=bytes.length%splitLength;
		if(y!=0){
			x=bytes.length/splitLength+1;
		}else{
			x=bytes.length/splitLength;
		}
		byte[][] arrays=new byte[x][];
		byte[] array;
		for(int i=0; i<x; i++){
			if(i==x-1 && bytes.length%splitLength!=0){
				array=new byte[bytes.length%splitLength];
				System.arraycopy(bytes, i*splitLength, array, 0, bytes.length%splitLength);
			}else{
				array=new byte[splitLength];
				System.arraycopy(bytes, i*splitLength, array, 0, splitLength);
			}
			arrays[i]=array;
		}
		return arrays;
	}
	//byte數組轉十六進制字符串
	public static String bytesToHexString(byte[] bytes) {
    StringBuffer sb = new StringBuffer(bytes.length);
    String sTemp;
    for (int i = 0; i < bytes.length; i++) {
      sTemp = Integer.toHexString(0xFF & bytes[i]);
      if (sTemp.length() < 2)
        sb.append(0);
      sb.append(sTemp.toUpperCase());
    }
    return sb.toString();
  }
	//十六進制字符串轉byte數組
	public static byte[] hexString2Bytes(String hex) {
    int len = (hex.length() / 2);
    hex=hex.toUpperCase();
    byte[] result = new byte[len];
    char[] achar = hex.toCharArray();
    for (int i = 0; i < len; i++) {
      int pos = i * 2;
      result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
    }
    return result;
  }
	private static byte toByte(char c) {
    byte b = (byte) "0123456789ABCDEF".indexOf(c);
    return b;
  }
}

運行結果

加密后:0681CEA1051892E038CEB83EDCD5D549B61F31787FEF92123E0961F2E8FAF2590BAD88A2341C9684E6B3791D03D95BDFFF852EFD79B6748364A8A2369828A6E5752FE3910EA162970BAED78ABDE37F2DB2523CB3B47A46A9B2BC2C2C828D6024913B9B52E43837BCD0A6DF74BE14EB593EB732351961EA33732CE5347281EEAE
解密后:hello world

最后,有一點必須強調,因為中間磨了我不少時間。

中間加密后,如果要打印出來,必須以十六進制或者BCD碼的形式打印,不能new String(byte[])后,再從這個String里getbytes(),也不要用base64,不然會破壞原數據。

比如,舉個例子:

byte[ ] bytes=new byte[ ]{108, -56, 111, 34, -67}; 
byte[ ] newBytes=new String(bytes).getBytes(); 
StringBuffer sb=new StringBuffer(); 
for(int i=0; i<newBytes.length; i++){ 
  sb.append(newBytes[i]+"|"); 
} 
System.out.println(sb.toString()); 

將一個byte數組new String后再getbytes出來后,看看運行結果:

108|-56|111|34|63

最后一個byte由-67變為了63,這個務必注意啊~

總結

以上就是本文關于java加解密RSA使用方法代碼示例的全部內容,希望對大家有所幫助。歡迎參閱:Java大數字運算之BigInteger 、Java探索之Thread+IO文件的加密解密代碼實例等,有什么問題可以留言指出,歡迎大家交流討論。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

睢宁县| 石嘴山市| 娱乐| 东平县| 岫岩| 宜川县| 山西省| 邓州市| 桃园市| 新竹县| 临西县| 皮山县| 永宁县| 长寿区| 喀什市| 镇宁| 潮州市| 胶州市| 东港市| 瑞金市| 长阳| 定远县| 融水| 定南县| 甘德县| 周口市| 荥经县| 石家庄市| 桂阳县| 葵青区| 桦南县| 藁城市| 淅川县| 安义县| 吉安市| 八宿县| 墨脱县| 建始县| 南乐县| 金溪县| 石嘴山市|