Recently, I have done a project, in which I need to use an RSASSA-PSS-2048-SHA256 algorithm to sign the data sent. I found many on the Internet, but I didn't find the right one. Now, I'm almost done, so I want to sort this out. I'm a rookie. If there is anything wrong in the document, please help me to point out. Thank you
All right, no more nonsense, just go to the code
/** * SHA256WithRSA autograph * * @param data * @return * @throws Exception */ public static String sign256(String data, String privateKeyStr) throws Exception { PrivateKey privateKey = loadPrivateKey(privateKeyStr); Signature signature = Signature.getInstance("SHA256WithRSA/PSS", new BouncyCastleProvider()); signature.initSign(privateKey); signature.update(data.getBytes("UTF-8")); return new String(Base64.encode(signature.sign(), Base64.NO_WRAP)); } /** * Load private key from string < br > * PKCS8EncodedKeySpec (PKCs × 8 encoded Key instruction) is used when loading. * * @return * @throws Exception */ public static PrivateKey loadPrivateKey(String private_key) throws Exception { try { byte[] buffer = Base64.decode(private_key, 0); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return (RSAPrivateKey) keyFactory.generatePrivate(keySpec); } catch (NoSuchAlgorithmException e) { throw new Exception("No algorithm is available."); } catch (InvalidKeySpecException e) { throw new Exception("Private key illegal"); } catch (NullPointerException e) { throw new Exception("Private key data is empty"); } }
It didn't work because
Signature signature = Signature.getInstance("SHA256withRSA/PSS","BC"); this line of code may have incorrect parameters
After a lot of investigation, it was changed to
Signature signature = Signature.getInstance("SHA256WithRSA/PSS", new BouncyCastleProvider()); then the verification is passed
The BouncyCastleProvider() class is in a bcprov-ext-jdk15on-158.jar (this jar can be downloaded after baidu searches)
Maybe it's different from other people's problems. I only record my problems here. Don't spray if you don't like it. Thank you