RSA算法加密,加密/解密方式分为通过证书/字符串进行加密解密
一、加密
1、加密方案
为避免用户需要在多个业务系统上进行登陆和注销,通过RSA单点登录方式来进行认证管理。
加密方式:通常是由用户信息和时间戳组成的信息串,利用预定的公钥对字符串进行加密。
2、公钥的获取
获取公钥有两种方式证书加密和公钥字符串加密
2.1、证书加密
File certFile = new File(“证书地址”);
//公钥是否存在
if (!certFile.exists()) {
throw new BOException("公钥证书不存在,请联系维护人员。");
}
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate)cf.generateCertificate(
new FileInputStream(certFile));
PublicKey publicKey = cert.getPublicKey();
2.2、公钥字符串加密
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.decodeBase64(
(“公钥加密字符串”).getBytes()));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(keySpec);
3、通过公钥加密获取加密字符串
//原字符串
String source = “{user:'zhangshang',expire: '2021/02/03 14:20:18'}”;
//pubKey为上面生成的公钥
//outStr为最终生成的加密串
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
//返回加密字符串
String outStr = new String(Base64.encode(cipher.doFinal(
source.getBytes(CHAR_ENCODING))), CHAR_ENCODING);
二、解密
1、解密方案
首先获取私钥、然后通过私钥进行解密
2、获取私钥
获取私钥有两种方式证书解密获取和私钥字符串解密获取
2.1、证书解密
String privateKeyPath=”证书地址”;
String privateKeyPassword =”私钥密码”;
KeyStore ks = KeyStore.getInstance("PKCS12");
FileInputStream fis = new FileInputStream(privateKeyPath);
char[] nPassword = null;
if ((privateKeyPassword == null) || privateKeyPassword.trim().equals("")){
nPassword = null;
} else {
nPassword = privateKeyPassword.toCharArray();
}
ks.load(fis, nPassword);
fis.close();
Enumeration enumas = ks.aliases();
String keyAlias = null;
if (enumas.hasMoreElements()) {
keyAlias = (String)enumas.nextElement();
}
PrivateKey prikey = (PrivateKey) ks.getKey(keyAlias, nPassword);
2.2、私钥字符串解密
String singleLogin_privateKey =”私钥字符串”;
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(
Base64.decodeBase64(singleLogin_privateKey.getBytes()));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
3、通过私钥解密解析字符串
//privateKey为上面加密的私钥
String cryStr =”需要解析的字符串”;
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] content = Base64.decode2(cryStr);
if(null == content){
return new String("");
}
byte[] encrypted = cipher.doFinal(content);
String outstr = new String(encrypted);
//“{user:'zhangshang',expire: '2021/02/03 14:20:18'}”;
RSA加密算法详解与实现
本文介绍了RSA加密算法,包括通过证书和字符串进行的加密解密过程。在加密环节,详细阐述了加密方案,如使用公钥对包含用户信息和时间戳的字符串加密,以及公钥的获取方式。在解密部分,讲解了如何使用私钥进行解密,并列举了获取私钥的两种方法。
6883

被折叠的 条评论
为什么被折叠?



