JDK8的JCE是不支持读取PEM文件的。需要使用bouncycastle。
项目需求,使用SHA1WithRSA算法,对接口数据做签名。
代码如下:
@Service
class SignService {
private static Logger LOG = LoggerFactory.getLogger(SignService.class);
@Autowired
private Config config;
private Signature signature;
@PostConstruct
private void init() {
try {
PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec(
getDecoder().decode(config.getPrivateKey().getBytes(ISO_8859_1)));
KeyFactory factory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = factory.generatePrivate(priKeySpec);
signature = Signature.getInstance("SHA1WithRSA");
signature.initSign(privateKey);
} catch (NoSuchAlgorithmException |
/*InvalidAlgorithmParameterException |*/
InvalidKeySpecException |
InvalidKeyException ex) {
LOG.warn("RSA init error: {}.", ex);
}
}
String signAndEncode(String source) {
if (Objects.isNull(source)) {
return null;
} else {
return sign(source)
.map(this::encode)
.orElse("");
}
}
private String encode(byte[] source) {
retur