package jdbc.pro.lin;

 import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map; import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException; import org.apache.commons.codec.binary.Base64; public class MyRSA {
public static final String KEY_ALGORITHM = "RSA";
/** 貌似默认是RSA/NONE/PKCS1Padding,未验证 */
public static final String CIPHER_ALGORITHM = "RSA/ECB/PKCS1Padding";
public static final String PUBLIC_KEY = "publicKey";
public static final String PRIVATE_KEY = "privateKey"; /** RSA密钥长度必须是64的倍数,在512~65536之间。默认是1024 */
public static final int KEY_SIZE = 2048; public static final String PLAIN_TEXT = "MANUTD is the greatest club in the world"; public static void main(String[] args) {
Map<String, byte[]> keyMap = generateKeyBytes(); // 加密
PublicKey publicKey = restorePublicKey(keyMap.get(PUBLIC_KEY)); byte[] encodedText = RSAEncode(publicKey, PLAIN_TEXT.getBytes());
System.out.println("RSA encoded: " + Base64.encodeBase64String(encodedText)); // 解密
PrivateKey privateKey = restorePrivateKey(keyMap.get(PRIVATE_KEY));
System.out.println("RSA decoded: "
+ RSADecode(privateKey, encodedText));
} /**
* 生成密钥对。注意这里是生成密钥对KeyPair,再由密钥对获取公私钥
*
* @return
*/
public static Map<String, byte[]> generateKeyBytes() { try {
KeyPairGenerator keyPairGenerator = KeyPairGenerator
.getInstance(KEY_ALGORITHM);
keyPairGenerator.initialize(KEY_SIZE);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); Map<String, byte[]> keyMap = new HashMap<String, byte[]>();
keyMap.put(PUBLIC_KEY, publicKey.getEncoded());
keyMap.put(PRIVATE_KEY, privateKey.getEncoded());
return keyMap;
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
} /**
* 还原公钥,X509EncodedKeySpec 用于构建公钥的规范
*
* @param keyBytes
* @return
*/
public static PublicKey restorePublicKey(byte[] keyBytes) {
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes); try {
KeyFactory factory = KeyFactory.getInstance(KEY_ALGORITHM);
PublicKey publicKey = factory.generatePublic(x509EncodedKeySpec);
return publicKey;
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
} /**
* 还原私钥,PKCS8EncodedKeySpec 用于构建私钥的规范
*
* @param keyBytes
* @return
*/
public static PrivateKey restorePrivateKey(byte[] keyBytes) {
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(
keyBytes);
try {
KeyFactory factory = KeyFactory.getInstance(KEY_ALGORITHM);
PrivateKey privateKey = factory
.generatePrivate(pkcs8EncodedKeySpec);
return privateKey;
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
} /**
* 加密,三步走。
*
* @param key
* @param plainText
* @return
*/
public static byte[] RSAEncode(PublicKey key, byte[] plainText) { try {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key);
return cipher.doFinal(plainText);
} catch (NoSuchAlgorithmException | NoSuchPaddingException
| InvalidKeyException | IllegalBlockSizeException
| BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null; } /**
* 解密,三步走。
*
* @param key
* @param encodedText
* @return
*/
public static String RSADecode(PrivateKey key, byte[] encodedText) { try {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key);
return new String(cipher.doFinal(encodedText));
} catch (NoSuchAlgorithmException | NoSuchPaddingException
| InvalidKeyException | IllegalBlockSizeException
| BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null; }
}

几点注意:

1.用到了KeyFactory。

2.用到了公私钥的规范。

3.RSA密钥长度从512~65536,必须是64的整数倍

最新文章

  1. zxing 一维码部分深入分析与实际应用,识别卡片数量,Android数卡器
  2. jQuery简单实例
  3. hdu-5927 Auxiliary Set(树形dp)
  4. C# .NET3.5 改为 到.NET2.0 时 TypedTableBase 报错解决方法
  5. JAVA/PHP/C#版RSA验签--转
  6. AlertDialog具体解释
  7. edittext设置为密文显示
  8. 文件系统的几种类型:ext3, s…
  9. HiveQL DML 常用QL示例资料
  10. 笔记9 AOP练习3(通过注解引入新功能 )
  11. 关于 Docker 镜像的操作,看完这篇就够啦 !(下)
  12. Linux 基础学习:文件权限与种类
  13. python-面向对象之继承
  14. Android Selinux
  15. STL的基本介绍
  16. [CF1060F]Shrinking Tree[树dp+组合计数]
  17. preg_match用法
  18. Pycharm 问题:Clear Read-Only Status
  19. ACM-ICPC 2018 徐州赛区网络预赛 Solution
  20. 获取Spring的ApplicationContext的几种方式

热门文章

  1. OA学习笔记-006-SPRING2.5与hibernate3.5整合
  2. POP3、SMTP、IMAP和Exchange的区别在哪里?
  3. 2.5.6 使用progressDialog创建进度对话框
  4. [转]Unity 3D旋转矢量方向及二维平面基于一点选择另一点(Rotate a Vector3 direction &amp; Rotate a point about another point in 2D )
  5. devi into python 笔记(三)callable getattr lambda表达式
  6. ASPNET5中的那些K
  7. win7常用键
  8. 为虚拟机搭建MacOSX系统
  9. 《Linear Algebra and Its Applications》-chaper1-线性方程组- 线性变换
  10. Closure Compiler(封闭编辑器), Closure Inspector, Closure Templates, 封闭图书馆(Closure Library) Google- 摘自网络