Java 在Android上验证数字签名
我正在开发一个Android应用程序,需要对html文档进行数字签名。 文档以JSON格式驻留在数据库中。 我使用在其他问题上找到的BASH脚本在本地对文档进行签名:Java 在Android上验证数字签名,java,android,json,digital-signature,Java,Android,Json,Digital Signature,我正在开发一个Android应用程序,需要对html文档进行数字签名。 文档以JSON格式驻留在数据库中。 我使用在其他问题上找到的BASH脚本在本地对文档进行签名: openssldgst-sha1 someHTMLDoc.html>hash openssl rsautl-sign-inkey privateKey.pem-keyform pem-in hash>signature.bin 私钥是使用以下方法生成的: openssl genpkey -algorithm RSA -pkeyop
openssldgst-sha1 someHTMLDoc.html>hash
openssl rsautl-sign-inkey privateKey.pem-keyform pem-in hash>signature.bin
私钥是使用以下方法生成的:
openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -pkeyopt rsa_keygen_pubexp:3 -out privateKey.pem
openssl pkey -in privateKey.pem -out publicKey.pem -pubout
公钥是使用以下方法生成的:
openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -pkeyopt rsa_keygen_pubexp:3 -out privateKey.pem
openssl pkey -in privateKey.pem -out publicKey.pem -pubout
我想验证signature.bin中创建的签名以及应用程序中someHTMLDoc.html中的数据
我将html和签名作为JSON对象发送,例如:
{ "data" : "<html><body></body></html>", "signature":"6598 13a9 b12b 21a9 ..... " }
有人能帮忙吗?我做错了什么
我缺少一些字节转换吗?也许JSON对象正在影响签名
签名应该包含原始文件包含的\n(换行符),还是应该不包含在JSON文件中
非常感谢您的帮助。数字签名是一种计算数据(C)摘要(函数H)并使用非对称加密算法(函数E)对其进行加密以生成密码文本的过程: 签名验证采用签名对给定签名进行解密(函数D)-只有在解密中使用的公钥与加密中使用的私钥配对时,才会产生H(C),并计算数据摘要以检查两个摘要是否匹配:
H(C) == D(E(H(C)))
从这一点可以清楚地看出,为了验证签名,给定给散列函数(C)的字节必须完全相同
在您的情况下,它们不是,因为当您使用openssl-dgst
计算摘要时,输出(右侧的H(C))实际上类似于:
SHA1(someHTMLDoc.html)= 22596363b3de40b06f981fb85d82312e8c0ed511
这是RSA加密的输入
当您验证签名时,摘要的输出(左侧的H(C))是原始字节,例如十六进制:
22596363b3de40b06f981fb85d82312e8c0ed511
因此,您最终加密字节以生成(右侧的H(C)):
并与字节(左侧的H(C))进行比较:
您还需要将-sign
与openssl dgst
一起使用,以获得正确的输出格式(请参阅)
因此,在OpenSSL方面,请执行以下操作:
openssl dgst -sha1 -sign privateKey.pem someHTMLDoc.html > signature.bin
在Java方面,请执行以下操作:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.KeyFactory;
import java.security.Signature;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;
import org.spongycastle.util.io.pem.PemObject;
import org.spongycastle.util.io.pem.PemReader;
public class VerifySignature {
public static void main(final String[] args) throws Exception {
try (PemReader reader = publicKeyReader(); InputStream data = data(); InputStream signatureData = signature()) {
final PemObject publicKeyPem = reader.readPemObject();
final byte[] publicKeyBytes = publicKeyPem.getContent();
final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
final X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyBytes);
final RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(publicKeySpec);
final Signature signature = Signature.getInstance("SHA1withRSA");
signature.initVerify(publicKey);
final byte[] buffy = new byte[16 * 1024];
int read = -1;
while ((read = data.read(buffy)) != -1) {
signature.update(buffy, 0, read);
}
final byte[] signatureBytes = new byte[publicKey.getModulus().bitLength() / 8];
signatureData.read(signatureBytes);
System.out.println(signature.verify(signatureBytes));
}
}
private static InputStream data() throws FileNotFoundException {
return new FileInputStream("someHTMLDoc.html");
}
private static PemReader publicKeyReader() throws FileNotFoundException {
return new PemReader(new InputStreamReader(new FileInputStream("publicKey.pem")));
}
private static InputStream signature() throws FileNotFoundException {
return new FileInputStream("signature.bin");
}
}
我已经使用PEM对公钥进行解码,以使内容更可读、更易于使用。如果您有一个数字签名的XML文件(从web下载)和一个证书(.cer文件),并且您希望在android应用程序中验证数字签名,那么下面是代码:
public static boolean isXmlDigitalSignatureValid(String signedXmlFilePath,
String pubicKeyFilePath) throws Exception {
boolean validFlag;
File file = new File(signedXmlFilePath);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
doc.getDocumentElement().normalize();
NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
if (nl.getLength() == 0) {
throw new Exception("No XML Digital Signature Found, document is discarded");
}
FileInputStream fileInputStream = new FileInputStream(pubicKeyFilePath);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) cf.generateCertificate(fileInputStream);
PublicKey publicKey = cert.getPublicKey();
DOMValidateContext valContext = new DOMValidateContext(publicKey, nl.item(0));
XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
XMLSignature signature = fac.unmarshalXMLSignature(valContext);
validFlag = signature.validate(valContext);
return validFlag;
}
您需要两件事xmlFilePath和certificateFilePath
boolean verifySignature() {
boolean valid = false;
try {
File file = new File("xmlFilePath");
DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
f.setNamespaceAware(true);
Document doc = f.newDocumentBuilder().parse(file);
NodeList nodes = doc.getElementsByTagNameNS(Constants.SignatureSpecNS, "Signature");
if (nodes.getLength() == 0) {
throw new Exception("Signature NOT found!");
}
Element sigElement = (Element) nodes.item(0);
XMLSignature signature = new XMLSignature(sigElement, "");
CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream ims = new InputStream("certificateFilePath");
X509Certificate cert = (X509Certificate) cf.generateCertificate(ims);
if (cert == null) {
PublicKey pk = signature.getKeyInfo().getPublicKey();
if (pk == null) {
throw new Exception("Did not find Certificate or Public Key");
}
valid = signature.checkSignatureValue(pk);
} else {
valid = signature.checkSignatureValue(cert);
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "Failed signature " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
return valid;
}
如果你想用java而不是android studio来做这件事。代码如下:
public static boolean isXmlDigitalSignatureValid(String signedXmlFilePath,
String pubicKeyFilePath) throws Exception {
boolean validFlag;
File file = new File(signedXmlFilePath);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
doc.getDocumentElement().normalize();
NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
if (nl.getLength() == 0) {
throw new Exception("No XML Digital Signature Found, document is discarded");
}
FileInputStream fileInputStream = new FileInputStream(pubicKeyFilePath);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) cf.generateCertificate(fileInputStream);
PublicKey publicKey = cert.getPublicKey();
DOMValidateContext valContext = new DOMValidateContext(publicKey, nl.item(0));
XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
XMLSignature signature = fac.unmarshalXMLSignature(valContext);
validFlag = signature.validate(valContext);
return validFlag;
}
原因是,如果在AndroidStudio中使用相同的代码,则需要添加依赖项,有时也会令人困惑
如果您对阅读数字签名文档感兴趣,您可以阅读它,这是了解数字签名需求的有趣文档。我一直在尝试不同的方法,但没有成功,尝试从JSON对象中删除换行符,尝试过getBytes(“ASCII”)和getBytes(“UTF-8”)。您有任何异常吗?哪一个?我没有收到任何异常,它只是为
signCheck.verify()
返回False,我不确定我是否完全理解。。你要怎么加密呢?我是否应该只取dgst函数的22596363b3de40b06f981fb85d82312e8c0ed511
部分并用它签名?你能解释一下我该怎么做,而不是我犯了什么错误吗?我很难理解如何进行编写。请参阅我编辑的答案,您应该使用openssl dgst
和-sign
选项来生成JCE中签名实现所需的二进制输出。给这个人一个cookie!先生,你真是个天才!非常感谢。我会在19小时内给你奖金。再次非常感谢。
public static boolean isXmlDigitalSignatureValid(String signedXmlFilePath,
String pubicKeyFilePath) throws Exception {
boolean validFlag;
File file = new File(signedXmlFilePath);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
doc.getDocumentElement().normalize();
NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
if (nl.getLength() == 0) {
throw new Exception("No XML Digital Signature Found, document is discarded");
}
FileInputStream fileInputStream = new FileInputStream(pubicKeyFilePath);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) cf.generateCertificate(fileInputStream);
PublicKey publicKey = cert.getPublicKey();
DOMValidateContext valContext = new DOMValidateContext(publicKey, nl.item(0));
XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
XMLSignature signature = fac.unmarshalXMLSignature(valContext);
validFlag = signature.validate(valContext);
return validFlag;
}