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));
	}




展开阅读全文

没有更多推荐了,返回首页