RSA 算法: RSA是目前最有影响力的公钥加密算法,
明文--->公钥--->密文 密文-->密钥-->明文
通过这个我们可知 他是公钥对内容进行加密 进而借助密钥对文件进行解密 因为公钥和密钥是不一样的 所以 我们将其称为
非对称加密。
RSA由于public key<公钥> 和private key<密钥>的不同<也叫非对称算法加解密>,极大的提高了文件的安全性。
代码如下
KeyPairGenerator是一个引擎类可以生成私钥及其相关利用公钥算法初始化。
1:
1. //设置使用何种加密算法
2. KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
构造一个新实例的KeyPairGenerator算法使用的名称。
1. // 密钥位数
2. keyPairGen.initialize(1024);
3. // 密钥对
4. KeyPair keyPair = keyPairGen.generateKeyPair();
5. // 公钥
6. PublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
7. // 私钥
8. PrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
2:
为了公钥跟私钥可以传输和保存,因此可以设置为将他们转化成base64的编码,用到以下方法:
注意 这个地方就是将数据转化为base64编码
1. /****************************************
2. * 函数说明:getKeyString 根据key得到64位加密字符串
3. *
4. * @param key 密钥
5. * @throws Exception
6. * @return String 加密后的字符串
7. * @author 王洪贺 2013-8-21
8. ***************************************/
1. public static String getKeyString(Key key) throws Exception
2. {
3. byte[] keyBytes = key.getEncoded();
4. String s = base64Enc(keyBytes);
5. return s;
6. }
但加密跟解密的时候需要将base64位的编码转化为key的对象,所以用到以下两个方法:
1. /****************************************
2. * 函数说明:getPrivateKey 取得私钥
3. *
4. * @param key 私钥字符串
5. * @throws Exception
6. * @return PrivateKey 返回私钥
7. * @author 王洪贺 2013-8-21
8. ***************************************/
9. public static PrivateKey getPrivateKey(String key) throws Exception
10. {
11. byte[] keyBytes;
12. keyBytes = base64Dec(key);
13.
14. PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
15. KeyFactory keyFactory = KeyFactory.getInstance("RSA");
16. PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
17. return privateKey;
18. }
下面就是加密过程,很简单:
1. // 实例化加解密类
2. Cipher cipher = Cipher.getInstance("RSA");
3.
4. // 明文
5. byte[] plainText = "明文".getBytes();
6.
7. // 加密
8. cipher.init(Cipher.ENCRYPT_MODE, publicKe);
9. //将明文转化为根据公钥加密的密文,为byte数组格式
10. byte[] enBytes = cipher.doFinal(plainText);
11. //为了方便传输我们可以将byte数组转化为base64的编码
12. String str = base64Enc(enBytes );
复制代码
下面是解密过程,跟加密过程类似:
1. Cipher cipher = Cipher.getInstance("RSA");
2. cipher.init(Cipher.DECRYPT_MODE, privateKey);
3. //先将转为base64编码的加密后的数据转化为byte数组
4. byte[] enBytes = base64Dec(str);
5. //解密称为byte数组,应该为字符串数组最后转化为字符串
6. byte[] deBytes = cipher.doFinal(enBytes);
7. String strdecoded = new String(deBytes);
复制代码
总结 可得
KeyPairGenerator来确定是何种加密方式
比如RSA 另外 我们此时获得我们的公钥和密钥
2: 但是我们为了传输数据的时候更加容易 所以我们就借助base64编码
3:借助 Cipher类实现我们的我们的对传输内容进行加密和解密。