Java BouncyCastle,桌面/Android上签名的不同行为
我使用以下代码对数据进行签名:Java BouncyCastle,桌面/Android上签名的不同行为,java,android,cryptography,digital-signature,bouncycastle,Java,Android,Cryptography,Digital Signature,Bouncycastle,我使用以下代码对数据进行签名: static public byte[] sign(byte[] data, PrivateKey privateKey, int saltLength) throws Exception { Signature instance = Signature.getInstance("SHA256withRSA/PSS", provider); MGF1ParameterSpec mgf1ParameterSpec = new MGF1Paramete
static public byte[] sign(byte[] data, PrivateKey privateKey, int saltLength) throws Exception {
Signature instance = Signature.getInstance("SHA256withRSA/PSS", provider);
MGF1ParameterSpec mgf1ParameterSpec = new MGF1ParameterSpec("SHA-256");
PSSParameterSpec pssParameterSpec = new PSSParameterSpec("SHA-256", "MGF1",mgf1ParameterSpec , saltLength, 1);
instance.setParameter(pssParameterSpec);
instance.initSign(privateKey);
instance.update(data);
return instance.sign();
}
(代码与检查标志非常相似)
在桌面上,代码运行良好,可以使用其他平台(使用python、node等进行测试)检查签名
在Android上,“saltLength”不被读取,并且被强制为32位,所以如果使用另一个“saltLength”,我无法在其他平台上的设备上签名/验证签名。(我通过在桌面上强制使用saltLength值来验证它)
我真的不知道如何调试它,同样的Java代码在桌面或Android上启动时有不同的行为。知道如何在Android上强制使用“saltLength”吗?好的,在桌面和Android端进行了多次测试之后。。。 我仍然没有找到问题的根源(我猜是
java.security.Signature$SignatureImpl
的不同实现,但不确定……)
然而,我已经为遇到同样问题的任何人找到了解决办法。
我创建了以下类:
public class SHA256withRSACustomPadding extends PSSSignatureSpi {
public SHA256withRSACustomPadding(int padding) {
super(new RSABlindedEngine(), new PSSParameterSpec("SHA-256", "MGF1", new MGF1ParameterSpec("SHA-256"), padding, 1));
}
public void initSign(PrivateKey privateKey) throws InvalidKeyException {
engineInitSign(privateKey);
}
public void update(byte[] data) throws SignatureException {
engineUpdate(data,0,data.length);
}
public byte[] sign() throws SignatureException {
return engineSign();
}
public void initVerify(PublicKey publicKey) throws InvalidKeyException {
engineInitVerify(publicKey);
}
public boolean verify(byte[] data) throws SignatureException {
return engineVerify(data);
}
}
并将我以前的代码更新为:
static public byte[] sign(byte[] data, PrivateKey privateKey, int saltLength) throws Exception {
SHA256withRSACustomPadding instance = new SHA256withRSACustomPadding(padding);
instance.initSign(privateKey);
instance.update(data);
return instance.sign();
}
为什么不将saltLength的类型更改为Long。因为
PSSParameterSpec
构造函数是public PSSParameterSpec(String mdName、String mgfName、AlgorithmParameterSpec mgfSpec、int saltLen、int trailerField)