java中加密演算法Base64和RSA詳解和Android
手機的安全重要資訊容易被洩露的方式:
1.會從我們本地洩露 手機中毒等
2.會從伺服器洩露 伺服器人員將資訊賣出去等
3.半路上,網路傳輸的過程中 加密傳輸資料 手機連線WiFi,如果在WiFi上設定監聽資料,將關鍵的資訊攔截下來,就有可能盜取個人重要資訊。
-------常見的加密演算法:
AES 高階加密標準:DES的56位金鑰,比較容易被破解,所以漸漸使用AES替代,目前對稱加密中最流行演算法之一
DES 對稱加密演算法:加密和解密使用相同金鑰的演算法
RSA 公鑰加密演算法
MD5(即使用者發出的MD5加密資料和伺服器的MD5加密資料相匹對來驗證,我用來使用者名稱和密碼的驗證)
加密目的:防止資料資訊洩露.
-----------------------------------------
非對稱加密和對稱加密區別:對稱加密演算法在加密和解密時使用的是同一個祕鑰;而非對稱加密演算法需要兩個金鑰來進行加密和解密,這兩個祕鑰是公開金鑰(public key,簡稱公鑰)和私有金鑰(private key,簡稱私鑰)。
非對稱加密
加密 解密 規則不一致
伺服器會把公鑰傳送給每一個客戶端,客戶端在向伺服器傳送資料時,用公鑰進行加密但是,最終解密資料,是不用公鑰,而是通過私鑰完成,私鑰是不會發給別人,只會牢牢保護在伺服器端
公鑰 加密---------> 私鑰解密
私鑰 加簽---------->公鑰 驗籤
對稱加密
加密 解密 規則一致
-------------
RSA:
KeyPair :公私鑰對KeyPairGenerator 生成公私鑰對
Cipher 加密 解密功能
cipher.init(Cipher.ENCRYPT_MODE, publicKey); 設定為加密模式
cipher.init(Cipher.DECRYPT_MODE, privateKey); 設定為解密模式
cipher.doFinal 執行
java程式中,公鑰為 X509格式 私鑰為PKCS8格式
讀取公鑰:
讀取私鑰:<span style="white-space:pre"></span> X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(RSA); PublicKey publicKey = keyFactory.generatePublic(keySpec);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
程式碼如下:
顯示結果:public static void main(String[] args) throws NoSuchAlgorithmException { KeyPairGenerator kpg=KeyPairGenerator.getInstance("RSA"); KeyPair kp=kpg.genKeyPair(); System.out.println("私鑰:"+kp.getPrivate()); System.out.println("-------"); System.out.println("公鑰:"+kp.getPublic()); }
公鑰是直接顯示,而私鑰則並沒直接顯示
public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
KeyPairGenerator kpg=KeyPairGenerator.getInstance("RSA");
KeyPair keyPair=kpg.genKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();
String content="呵呵哈哈121adfs";
//加密
Cipher cipher=Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptDatas = cipher.doFinal(content.getBytes());
System.out.println("加密後的密文:"+new String(encryptDatas));
//解密
Cipher cipher1=Cipher.getInstance("RSA");
cipher1.init(Cipher.DECRYPT_MODE, privateKey);
byte[] dencryptDatas=cipher1.doFinal(encryptDatas);
System.out.println("加密回來的資料:"+new String(dencryptDatas));
}
要獲取公鑰和私鑰,則首先要開啟opensl外掛:
opensl生成指令:
RSA金鑰生成命令
生成RSA私鑰
openssl>genrsa -out rsa_private_key.pem 1024
生成RSA公鑰
openssl>rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem
將RSA私鑰轉換成PKCS8格式
openssl>pkcs8 -topk8 -inform PEM -in rsa_private_key.pem -outform PEM -nocrypt
-----------------------------------
註解:1.1024是指生成的密文的長度,當然越大越安全,但是耗時也越多.
2.公鑰生成的格式為x.509,私鑰生成的格式為PKCS#8,最後還要執行最後一句命令讓私鑰格式為PKCS8
---------獲取生成的公鑰和私慾
public static void main(String[] args) throws NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException,
IllegalBlockSizeException, BadPaddingException, IOException,
InvalidKeySpecException {
// TODO Auto-generated method stub
String content = "呵呵噠呵呵123ABCD+-*/";
// 讀取公鑰,進行加密
File publicKeyFile = new File(
"C:/Users/Administrator/Desktop/gsy/rsa_public_key.pem");
// 對原先的Base64格式進行解碼
byte[] publicBase64Datas = getKeyData(publicKeyFile);
byte[] publicOriginDatas = Base64.getDecoder()
.decode(publicBase64Datas);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicOriginDatas);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(keySpec);
// 加密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
//轉換加密編碼
byte[] encryptOriginDatas = cipher.doFinal(content.getBytes());
byte[] encryptBase64Datas =Base64.getEncoder().encode(encryptOriginDatas);
System.out.println(new String(encryptBase64Datas));
//提交資料
/*
* ----------------
*/
// 讀取公鑰,進行加密
File privateKeyFile = new File(
"C:/Users/Administrator/Desktop/gsy/privatekeyPKCS8.txt");
//私鑰解密
byte[] privateBase64Datas= getKeyData(privateKeyFile);
byte[] privateOriginDatas = Base64.getDecoder()
.decode(privateBase64Datas);
PKCS8EncodedKeySpec keySpec1 = new PKCS8EncodedKeySpec(privateOriginDatas);
KeyFactory keyFactory1= KeyFactory.getInstance("RSA");
PrivateKey privateKey1 = keyFactory1.generatePrivate(keySpec1);
//拿著之前的資料進行解碼
byte[] dencryptOriginDatas = Base64.getDecoder().decode(encryptBase64Datas);
Cipher cipher1=Cipher.getInstance("RSA");
cipher1.init(Cipher.DECRYPT_MODE, privateKey1);
byte[] dencryptDatas=cipher1.doFinal(dencryptOriginDatas);
System.out.println(new String(dencryptDatas));
}
private static byte[] getKeyData(File publicKeyFile) throws IOException {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(new FileInputStream(publicKeyFile)));
String str = null;
StringBuilder stringBuilder = new StringBuilder();
while ((str = bufferedReader.readLine()) != null) {
if (str.startsWith("--")) {
continue;
}
stringBuilder.append(str);
}
bufferedReader.close();
return stringBuilder.toString().getBytes();
// TODO Auto-generated method stub
}
---------Base64解析:
Base64和RSA相伴相生,主要是為了防止亂碼的產生
Base64其實不是加密解密演算法,只是個編碼解碼的演算法.
Android 自帶
Base64.Encoder 編碼
Base64.Decoder 解碼
加密的資料只是改變其形式不出現亂碼,但是發出和接手時資料未發生改變.---------Base64流程 1.原有的公鑰Key檔案中存放的Base64格式的公鑰,那麼我們讀取回來進行使用,就需要先用Base64解碼,獲取我們原有的公鑰位元組
2.加密資料
3.把加密的資料提交給伺服器,但是加密過的資料時一堆亂碼,直接提交會有問題,所以,我們再將這些亂碼用Base64進行編碼
4.將來伺服器收到我們的資料,需要先用Base64解碼,獲取到原始加密資料
5.用私鑰解密
以上是對加密演算法的詳細講解,但是一般使用我們會選擇別人已經完美搭建好的框架,這樣便可以快捷的使用加密方法.前人種樹後人乘涼,接下來就是快速的整合加密演算法這個工具.
-------------------Base64Utils工具類:
public class Base64Utils {
private static char[] base64EncodeChars = new char[]
{ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', '+', '/' };
private static byte[] base64DecodeChars = new byte[]
{ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53,
54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29,
30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1,
-1, -1, -1 };
/**
* 加密
*
* @param data
* @return
*/
public static String encode(byte[] data)
{
StringBuffer sb = new StringBuffer();
int len = data.length;
int i = 0;
int b1, b2, b3;
while (i < len)
{
b1 = data[i++] & 0xff;
if (i == len)
{
sb.append(base64EncodeChars[b1 >>> 2]);
sb.append(base64EncodeChars[(b1 & 0x3) << 4]);
sb.append("==");
break;
}
b2 = data[i++] & 0xff;
if (i == len)
{
sb.append(base64EncodeChars[b1 >>> 2]);
sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
sb.append(base64EncodeChars[(b2 & 0x0f) << 2]);
sb.append("=");
break;
}
b3 = data[i++] & 0xff;
sb.append(base64EncodeChars[b1 >>> 2]);
sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
sb.append(base64EncodeChars[((b2 & 0x0f) << 2) | ((b3 & 0xc0) >>> 6)]);
sb.append(base64EncodeChars[b3 & 0x3f]);
}
return sb.toString();
}
/**
* 解密
*
* @param str
* @return
*/
public static byte[] decode(String str)
{
try
{
return decodePrivate(str);
} catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
return new byte[]
{};
}
private static byte[] decodePrivate(String str) throws UnsupportedEncodingException
{
StringBuffer sb = new StringBuffer();
byte[] data = null;
data = str.getBytes("US-ASCII");
int len = data.length;
int i = 0;
int b1, b2, b3, b4;
while (i < len)
{
do
{
b1 = base64DecodeChars[data[i++]];
} while (i < len && b1 == -1);
if (b1 == -1)
break;
do
{
b2 = base64DecodeChars[data[i++]];
} while (i < len && b2 == -1);
if (b2 == -1)
break;
sb.append((char) ((b1 << 2) | ((b2 & 0x30) >>> 4)));
do
{
b3 = data[i++];
if (b3 == 61)
return sb.toString().getBytes("iso8859-1");
b3 = base64DecodeChars[b3];
} while (i < len && b3 == -1);
if (b3 == -1)
break;
sb.append((char) (((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2)));
do
{
b4 = data[i++];
if (b4 == 61)
return sb.toString().getBytes("iso8859-1");
b4 = base64DecodeChars[b4];
} while (i < len && b4 == -1);
if (b4 == -1)
break;
sb.append((char) (((b3 & 0x03) << 6) | b4));
}
return sb.toString().getBytes("iso8859-1");
}
}
--------RSAUtils工具類:
public class RSAUtils {
private static String RSA = "RSA";
/**
* 隨機生成RSA金鑰對(預設金鑰長度為1024)
*
* @return
*/
public static KeyPair generateRSAKeyPair() {
return generateRSAKeyPair(1024);
}
/**
* 隨機生成RSA金鑰對
*
* @param keyLength
* 金鑰長度,範圍:512~2048<br>
* 一般1024
* @return
*/
public static KeyPair generateRSAKeyPair(int keyLength) {
try {
KeyPairGenerator kpg = KeyPairGenerator.getInstance(RSA);
kpg.initialize(keyLength);
return kpg.genKeyPair();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
/**
* 用公鑰加密 <br>
* 每次加密的位元組數,不能超過金鑰的長度值減去11
*
* @param data
* 需加密資料的byte資料
* @param pubKey
* 公鑰
* @return 加密後的byte型資料
*/
public static byte[] encryptData(byte[] data, PublicKey publicKey) {
try {
Cipher cipher = Cipher.getInstance(RSA);
// 編碼前設定編碼方式及金鑰
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
// 傳入編碼資料並返回編碼結果
return cipher.doFinal(data);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 用私鑰解密
*
* @param encryptedData
* 經過encryptedData()加密返回的byte資料
* @param privateKey
* 私鑰
* @return
*/
public static byte[] decryptData(byte[] encryptedData, PrivateKey privateKey) {
try {
Cipher cipher = Cipher.getInstance(RSA);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(encryptedData);
} catch (Exception e) {
return null;
}
}
/**
* 通過公鑰byte[](publicKey.getEncoded())將公鑰還原,適用於RSA演算法
*
* @param keyBytes
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public static PublicKey getPublicKey(byte[] keyBytes)
throws NoSuchAlgorithmException, InvalidKeySpecException {
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
PublicKey publicKey = keyFactory.generatePublic(keySpec);
return publicKey;
}
/**
* 通過私鑰byte[]將公鑰還原,適用於RSA演算法
*
* @param keyBytes
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public static PrivateKey getPrivateKey(byte[] keyBytes)
throws NoSuchAlgorithmException, InvalidKeySpecException {
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
return privateKey;
}
/**
* 使用N、e值還原公鑰
*
* @param modulus
* @param publicExponent
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public static PublicKey getPublicKey(String modulus, String publicExponent)
throws NoSuchAlgorithmException, InvalidKeySpecException {
BigInteger bigIntModulus = new BigInteger(modulus);
BigInteger bigIntPrivateExponent = new BigInteger(publicExponent);
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(bigIntModulus,
bigIntPrivateExponent);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
PublicKey publicKey = keyFactory.generatePublic(keySpec);
return publicKey;
}
/**
* 使用N、d值還原私鑰
*
* @param modulus
* @param privateExponent
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public static PrivateKey getPrivateKey(String modulus,
String privateExponent) throws NoSuchAlgorithmException,
InvalidKeySpecException {
BigInteger bigIntModulus = new BigInteger(modulus);
BigInteger bigIntPrivateExponent = new BigInteger(privateExponent);
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(bigIntModulus,
bigIntPrivateExponent);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
return privateKey;
}
/**
* 從字串中載入公鑰
*
* @param publicKeyStr
* 公鑰資料字串
* @throws Exception
* 載入公鑰時產生的異常
*/
public static PublicKey loadPublicKey(String publicKeyStr) throws Exception {
try {
byte[] buffer = Base64Utils.decode(publicKeyStr);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
return (RSAPublicKey) keyFactory.generatePublic(keySpec);
} catch (NoSuchAlgorithmException e) {
throw new Exception("無此演算法");
} catch (InvalidKeySpecException e) {
throw new Exception("公鑰非法");
} catch (NullPointerException e) {
throw new Exception("公鑰資料為空");
}
}
/**
* 從字串中載入私鑰<br>
* 載入時使用的是PKCS8EncodedKeySpec(PKCS#8編碼的Key指令)。
*
* @param privateKeyStr
* @return
* @throws Exception
*/
public static PrivateKey loadPrivateKey(String privateKeyStr)
throws Exception {
try {
byte[] buffer = Base64Utils.decode(privateKeyStr);
// X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
} catch (NoSuchAlgorithmException e) {
throw new Exception("無此演算法");
} catch (InvalidKeySpecException e) {
throw new Exception("私鑰非法");
} catch (NullPointerException e) {
throw new Exception("私鑰資料為空");
}
}
/**
* 從檔案中輸入流中載入公鑰
*
* @param in
* 公鑰輸入流
* @throws Exception
* 載入公鑰時產生的異常
*/
public static PublicKey loadPublicKey(InputStream in) throws Exception {
try {
return loadPublicKey(readKey(in));
} catch (IOException e) {
throw new Exception("公鑰資料流讀取錯誤");
} catch (NullPointerException e) {
throw new Exception("公鑰輸入流為空");
}
}
/**
* 從檔案中載入私鑰
*
* @param keyFileName
* 私鑰檔名
* @return 是否成功
* @throws Exception
*/
public static PrivateKey loadPrivateKey(InputStream in) throws Exception {
try {
return loadPrivateKey(readKey(in));
} catch (IOException e) {
throw new Exception("私鑰資料讀取錯誤");
} catch (NullPointerException e) {
throw new Exception("私鑰輸入流為空");
}
}
/**
* 讀取金鑰資訊
*
* @param in
* @return
* @throws IOException
*/
private static String readKey(InputStream in) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String readLine = null;
StringBuilder sb = new StringBuilder();
while ((readLine = br.readLine()) != null) {
if (readLine.charAt(0) == '-') {
continue;
} else {
sb.append(readLine);
sb.append('\r');
}
}
return sb.toString();
}
/**
* 列印公鑰資訊
*
* @param publicKey
*/
public static void printPublicKeyInfo(PublicKey publicKey) {
RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
System.out.println("----------RSAPublicKey----------");
System.out.println("Modulus.length="
+ rsaPublicKey.getModulus().bitLength());
System.out.println("Modulus=" + rsaPublicKey.getModulus().toString());
System.out.println("PublicExponent.length="
+ rsaPublicKey.getPublicExponent().bitLength());
System.out.println("PublicExponent="
+ rsaPublicKey.getPublicExponent().toString());
}
public static void printPrivateKeyInfo(PrivateKey privateKey) {
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) privateKey;
System.out.println("----------RSAPrivateKey ----------");
System.out.println("Modulus.length="
+ rsaPrivateKey.getModulus().bitLength());
System.out.println("Modulus=" + rsaPrivateKey.getModulus().toString());
System.out.println("PrivateExponent.length="
+ rsaPrivateKey.getPrivateExponent().bitLength());
System.out.println("PrivatecExponent="
+ rsaPrivateKey.getPrivateExponent().toString());
}
}
----------------------整合使用 public static void main(String[] args) throws FileNotFoundException, Exception {
String content = "呵呵哈哈123ABD+-*/";
// 讀取公鑰,進行加密
File publicKeyFile = new File(
"C:/Users/Administrator/Desktop/gsy/rsa_public_key.pem");//公鑰路徑
//加密
PublicKey loadPublicKey = RSAUtils.loadPublicKey(new FileInputStream(publicKeyFile));
byte[] encryptData = RSAUtils.encryptData(content.getBytes(), loadPublicKey);
System.out.println(new String(encryptData));
//解密
File privateKeyFile = new File(
"C:/Users/Administrator/Desktop/gsy/privatekeyPKCS8.txt");//私鑰路徑
PrivateKey loadPrivateKey = RSAUtils.loadPrivateKey(new FileInputStream(privateKeyFile));
byte[] decryptData = RSAUtils.decryptData(encryptData, loadPrivateKey);
System.out.println(new String(decryptData));
}