其实我已经找到了解决方案。
问题在于以正确的方式加载公钥文件。
我将bouncycastle库添加到我的依赖项中:
<dependency> <groupId>org.bouncycastle</groupId> <artifactId>bcprov-jdk15on</artifactId> <version>1.47</version></dependency>
它提供了PemReader,它允许读取和加载未认证的公共密钥。
这是我的实用程序类:
import java.io.FileNotFoundException;import java.io.FileReader;import java.io.IOException;import java.io.UnsupportedEncodingException;import java.net.URLDeprer;import java.security.InvalidKeyException;import java.security.KeyFactory;import java.security.NoSuchAlgorithmException;import java.security.PublicKey;import java.security.Signature;import java.security.SignatureException;import java.security.spec.InvalidKeySpecException;import java.security.spec.X509EnpredKeySpec;import org.bouncycastle.util.io.pem.PemReader;import org.castor.util.base64Deprer;import fr.paris.lutece.portal.service.util.AppLogService;public final class PayboxUtil{ private static final String CHARSET = "utf-8"; private static final String ENCRYPTION_ALGORITHM = "RSA"; private static final String HASH_ENCRYPTION_ALGORITHM = "SHA1withRSA"; private PayboxUtil( ) { } public static boolean checkSign( String message, String sign, String keyPath ) { boolean ret = false; try { ret = PayboxUtil.verify( message, sign, PayboxUtil.getKey( keyPath ) ); } catch ( final FileNotFoundException e ) { AppLogService.error( e ); } catch ( final IOException e ) { AppLogService.error( e ); } catch ( final NoSuchAlgorithmException e ) { AppLogService.error( e ); } catch ( final InvalidKeySpecException e ) { AppLogService.error( e ); } catch ( final InvalidKeyException e ) { AppLogService.error( e ); } catch ( final SignatureException e ) { AppLogService.error( e ); } return ret; } private static PublicKey getKey( String keyPath ) throws NoSuchAlgorithmException, IOException, InvalidKeySpecException { final KeyFactory keyFactory = KeyFactory.getInstance( PayboxUtil.ENCRYPTION_ALGORITHM ); final PemReader reader = new PemReader( new FileReader( keyPath ) ); final byte[] pubKey = reader.readPemObject( ).getContent( ); final X509EnpredKeySpec publicKeySpec = new X509EnpredKeySpec( pubKey ); return keyFactory.generatePublic( publicKeySpec ); } private static boolean verify( String message, String sign, PublicKey publicKey ) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, UnsupportedEncodingException { final Signature sig = Signature.getInstance( PayboxUtil.HASH_ENCRYPTION_ALGORITHM ); sig.initVerify( publicKey ); sig.update( message.getBytes( PayboxUtil.CHARSET ) ); final byte[] bytes = base64Deprer.depre( URLDeprer.depre( sign, PayboxUtil.CHARSET ) ); return sig.verify( bytes ); }}您只需要将签名内容,签名和密钥路径传递给checkSign方法即可完成所有工作。



