rsa著名的非对称加密算法,具体实现我也不是很清楚,大概先要了解一下密码学,有一定基础才能去看的东东,这里就先介绍怎么使用rsa为我们服务。
首先openssl这是个集成了众多加密算法的工具,它将这一系列的算法整理在一起,是一个伟大的项目。
openssl genrsa -out private.key 1024
首先生成私钥,1024是私钥大小,越大越难被破译,同样加密解密所需的时间越长。
openssl rsa -in private.key -pubout -out public.key
这个是根据私钥生成公钥。注意私钥在java中使用时,需要通过PCKS#8转换,PCKS是美国RSA数据安全公司还有一堆人指定的密码学标准,其中#8是描述私钥的信息格式。
openssl pkcs8 -topk8 -nocrypt -in private.key -outform PEM -out java_private.key
公钥和私钥均可被用来加密解密。
公钥加密,私钥解密
私钥加签,公钥验签(这章没讲这个)。
上代码:
public static String encryptWithRSA(String msg, String keyPath, boolean isPrivate) { try { Cipher cipher = Cipher.getInstance("RSA"); if (isPrivate) { PrivateKey privateKey = loadRSAPrivateKey(keyPath); cipher.init(Cipher.ENCRYPT_MODE, privateKey); } else { PublicKey publicKey = loadRSAPublicKey(keyPath); cipher.init(Cipher.ENCRYPT_MODE, publicKey); } byte[] encryptByteMsg = cipher.doFinal(msg.getBytes("utf-8")); String encryptMsg = Base64.getEncoder().encodeToString(encryptByteMsg); logger.info("get encryptMsg:[{}]", encryptByteMsg); return encryptMsg; } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | BadPaddingException | UnsupportedEncodingException | IllegalBlockSizeException e) { logger.error("encrypt error", e); throw new FlyException(FrameworkExceptionCode.ENCRYPTERROR.getCode(), FrameworkExceptionCode.ENCRYPTERROR.getMsg()); } }
public static String decryptMsgWithRSA(String encryptMsg, String keyPath, boolean isPrivate) { try { Cipher cipher = Cipher.getInstance("RSA"); if (isPrivate) { PrivateKey privateKey = loadRSAPrivateKey(keyPath); cipher.init(Cipher.DECRYPT_MODE, privateKey); } else { PublicKey publicKey = loadRSAPublicKey(keyPath); cipher.init(Cipher.DECRYPT_MODE, publicKey); } byte[] encryptByte = Base64.getDecoder().decode(encryptMsg.getBytes()); byte[] plainByteMsg = cipher.doFinal(encryptByte); return new String(plainByteMsg); } catch (NoSuchAlgorithmException |NoSuchPaddingException |InvalidKeyException|BadPaddingException|IllegalBlockSizeException e) { logger.error("decrypt error!",e); throw new FlyException(FrameworkExceptionCode.DECRYPTERROR.getCode(),FrameworkExceptionCode.DECRYPTERROR.getMsg()); } }