k.e.book.common.utils.RSAEncryptor Maven / Gradle / Ivy
package k.e.book.common.utils;
import org.springframework.util.Base64Utils;
import org.springframework.util.StringUtils;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.X509EncodedKeySpec;
import java.util.Objects;
public class RSAEncryptor {
public static final String RSA_ALGORITHM = "RSA";
/**
* 签名算法
*/
public static final String SIGN_ALGORITHMS = "SHA1WithRSA";
/**
* 验签
*
* @param content
* @param charset
* @param publicKey
* @param sign
* @return
* @throws Exception
*/
public static boolean doVerify(String content, String charset, String publicKey, String sign) {
try {
PublicKey pubKey = getPublicKey(publicKey);
Signature signature = Signature.getInstance(SIGN_ALGORITHMS);
signature.initVerify(pubKey);
if (StringUtils.isEmpty(charset)) {
signature.update(content.getBytes());
} else {
signature.update(content.getBytes(charset));
}
return signature.verify(Base64Utils.decodeFromString(sign));
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* 得到公钥
*
* @param base64PubKey 密钥字符串(经过base64编码)
* @return PublicKey
*/
public static PublicKey getPublicKey(String base64PubKey) throws Exception {
Objects.requireNonNull(base64PubKey, "base64 public key is null.");
byte[] keyBytes = Base64Utils.decodeFromString(base64PubKey);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
return keyFactory.generatePublic(keySpec);
}
}