在 Android 上验证数字签名
Verify Digital Signature on Android
我正在开发需要对 html 文档进行数字签名的 Android 应用程序。
该文档以 JSON 形式驻留在数据库中。
我正在使用我在其他一些 SO 问题上找到的 BASH 脚本在本地签署文档:
openssl dgst -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
Public 密钥是使用 :
生成的
openssl pkey -in privateKey.pem -out publicKey.pem -pubout
我想验证 Signature.bin 中创建的签名以及 someHTMLDoc.html 中的数据,回到应用程序中。
我发送 html 和签名作为 JSON 对象 ex:
{ "data" : "<html><body></body></html>", "signature":"6598 13a9 b12b 21a9 ..... " }
android 应用程序在共享首选项中持有 Public 密钥,如下所示:
-----BEGIN PUBLIC KEY-----
MIIBIDANBgkqhkiG9w0AAAEFAAOCAQ0AvniCAKCAQEAvni/NSEX3Rhx91HkJl85
\nx1noyYET ......
Notice the "\n" (newline) in there (was automatically added when copying string from publicKey.pem to Android Gradle Config.
好了,所有的准备工作都做好了,下面是问题。
我正在尝试验证密钥但没有成功。
我正在使用以下代码:
private boolean verifySignature(String data, String signature) {
InputStream is = null;
try {
is = new ByteArrayInputStream(Config.getDogbarPublic().getBytes("UTF-8")); //Read DogBar Public key
BufferedReader br = new BufferedReader(new InputStreamReader(is));
List<String> lines = new ArrayList<String>();
String line;
while ((line = br.readLine()) != null)
lines.add(line);
// removes the first and last lines of the file (comments)
if (lines.size() > 1 && lines.get(0).startsWith("-----") && lines.get(lines.size() - 1).startsWith("-----")) {
lines.remove(0);
lines.remove(lines.size() - 1);
}
// concats the remaining lines to a single String
StringBuilder sb = new StringBuilder();
for (String aLine : lines)
sb.append(aLine);
String key = sb.toString();
byte[] keyBytes = Base64.decode(key.getBytes("utf-8"), Base64.DEFAULT);
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(spec);
Signature signCheck = Signature.getInstance("SHA1withRSA"); //Instantiate signature checker object.
signCheck.initVerify(publicKey);
signCheck.update(data.getBytes());
return signCheck.verify(signature.getBytes()); //verify signature with public key
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
有人能帮忙吗?我究竟做错了什么 ?
我是否遗漏了一些字节转换?也许 JSON 对象正在影响签名?
签名是否应该包含原始文件包含的 \n(换行符),或者在 JSON 文件中是否应该包含?
在此先感谢您的所有帮助,非常感谢。
数字签名是计算数据(C)的摘要(函数H),并用非对称加密算法(函数E)加密生成密文(S)的过程:
S = E(H(C))
签名验证采用签名解密给定的签名(函数 D)——仅当解密中使用的 public 密钥与加密中使用的私钥配对时才会产生 H(C),并计算数据摘要以检查两个摘要是否匹配:
H(C) == D(E(H(C)))
从这里可以清楚地看出,赋予哈希函数 (C) 的字节必须完全相同才能使签名生效。
在你的情况下它们不是,因为当你使用 openssl dgst
计算摘要时,输出(右边的 H(C))实际上是这样的:
SHA1(someHTMLDoc.html)= 22596363b3de40b06f981fb85d82312e8c0ed511
这是RSA加密的输入。
当您验证签名时,摘要的输出(左侧的 H(C))是 raw 字节,例如十六进制:
22596363b3de40b06f981fb85d82312e8c0ed511
所以你最终加密字节以产生(右侧的 H(C)):
0000000: 5348 4131 2873 6f6d 6548 746d 6c44 6f63 SHA1(someHtmlDoc
0000010: 2e68 746d 6c29 3d20 3232 3539 3633 3633 .html)= 22596363
0000020: 6233 6465 3430 6230 3666 3938 3166 6238 b3de40b06f981fb8
0000030: 3564 3832 3331 3265 3863 3065 6435 3131 5d82312e8c0ed511
0000040: 0a .
并与字节(左侧的 H(C))进行比较:
0000000: 2259 6363 b3de 40b0 6f98 1fb8 5d82 312e "Ycc..@.o...].1.
0000010: 8c0e d511 ....
您还需要使用 -sign
和 openssl dgst
以获得正确的输出格式(参见 Difference between openSSL rsautl and 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");
}
}
我使用 Spongy Castle 对 public 密钥进行 PEM 解码,使内容更具可读性和更易于使用。
如果您有数字签名的 XML 文件(从网络下载)和证书(.cer 文件)并且您想在 android 应用程序中验证数字签名,那么这里是代码:
你需要两个东西 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 工作室中进行。这是代码:
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中使用相同的代码,你将需要添加依赖,有时也会混淆。
如果您有兴趣阅读数字签名文档,可以阅读www.xml.com/post这是一个有趣的文档,可以帮助您了解数字签名的必要性。
我正在开发需要对 html 文档进行数字签名的 Android 应用程序。 该文档以 JSON 形式驻留在数据库中。 我正在使用我在其他一些 SO 问题上找到的 BASH 脚本在本地签署文档:
openssl dgst -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
Public 密钥是使用 :
生成的openssl pkey -in privateKey.pem -out publicKey.pem -pubout
我想验证 Signature.bin 中创建的签名以及 someHTMLDoc.html 中的数据,回到应用程序中。
我发送 html 和签名作为 JSON 对象 ex:
{ "data" : "<html><body></body></html>", "signature":"6598 13a9 b12b 21a9 ..... " }
android 应用程序在共享首选项中持有 Public 密钥,如下所示:
-----BEGIN PUBLIC KEY-----
MIIBIDANBgkqhkiG9w0AAAEFAAOCAQ0AvniCAKCAQEAvni/NSEX3Rhx91HkJl85
\nx1noyYET ......
Notice the "\n" (newline) in there (was automatically added when copying string from publicKey.pem to Android Gradle Config.
好了,所有的准备工作都做好了,下面是问题。 我正在尝试验证密钥但没有成功。
我正在使用以下代码:
private boolean verifySignature(String data, String signature) {
InputStream is = null;
try {
is = new ByteArrayInputStream(Config.getDogbarPublic().getBytes("UTF-8")); //Read DogBar Public key
BufferedReader br = new BufferedReader(new InputStreamReader(is));
List<String> lines = new ArrayList<String>();
String line;
while ((line = br.readLine()) != null)
lines.add(line);
// removes the first and last lines of the file (comments)
if (lines.size() > 1 && lines.get(0).startsWith("-----") && lines.get(lines.size() - 1).startsWith("-----")) {
lines.remove(0);
lines.remove(lines.size() - 1);
}
// concats the remaining lines to a single String
StringBuilder sb = new StringBuilder();
for (String aLine : lines)
sb.append(aLine);
String key = sb.toString();
byte[] keyBytes = Base64.decode(key.getBytes("utf-8"), Base64.DEFAULT);
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(spec);
Signature signCheck = Signature.getInstance("SHA1withRSA"); //Instantiate signature checker object.
signCheck.initVerify(publicKey);
signCheck.update(data.getBytes());
return signCheck.verify(signature.getBytes()); //verify signature with public key
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
有人能帮忙吗?我究竟做错了什么 ?
我是否遗漏了一些字节转换?也许 JSON 对象正在影响签名?
签名是否应该包含原始文件包含的 \n(换行符),或者在 JSON 文件中是否应该包含?
在此先感谢您的所有帮助,非常感谢。
数字签名是计算数据(C)的摘要(函数H),并用非对称加密算法(函数E)加密生成密文(S)的过程:
S = E(H(C))
签名验证采用签名解密给定的签名(函数 D)——仅当解密中使用的 public 密钥与加密中使用的私钥配对时才会产生 H(C),并计算数据摘要以检查两个摘要是否匹配:
H(C) == D(E(H(C)))
从这里可以清楚地看出,赋予哈希函数 (C) 的字节必须完全相同才能使签名生效。
在你的情况下它们不是,因为当你使用 openssl dgst
计算摘要时,输出(右边的 H(C))实际上是这样的:
SHA1(someHTMLDoc.html)= 22596363b3de40b06f981fb85d82312e8c0ed511
这是RSA加密的输入。
当您验证签名时,摘要的输出(左侧的 H(C))是 raw 字节,例如十六进制:
22596363b3de40b06f981fb85d82312e8c0ed511
所以你最终加密字节以产生(右侧的 H(C)):
0000000: 5348 4131 2873 6f6d 6548 746d 6c44 6f63 SHA1(someHtmlDoc
0000010: 2e68 746d 6c29 3d20 3232 3539 3633 3633 .html)= 22596363
0000020: 6233 6465 3430 6230 3666 3938 3166 6238 b3de40b06f981fb8
0000030: 3564 3832 3331 3265 3863 3065 6435 3131 5d82312e8c0ed511
0000040: 0a .
并与字节(左侧的 H(C))进行比较:
0000000: 2259 6363 b3de 40b0 6f98 1fb8 5d82 312e "Ycc..@.o...].1.
0000010: 8c0e d511 ....
您还需要使用 -sign
和 openssl dgst
以获得正确的输出格式(参见 Difference between openSSL rsautl and 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");
}
}
我使用 Spongy Castle 对 public 密钥进行 PEM 解码,使内容更具可读性和更易于使用。
如果您有数字签名的 XML 文件(从网络下载)和证书(.cer 文件)并且您想在 android 应用程序中验证数字签名,那么这里是代码:
你需要两个东西 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 工作室中进行。这是代码:
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中使用相同的代码,你将需要添加依赖,有时也会混淆。
如果您有兴趣阅读数字签名文档,可以阅读www.xml.com/post这是一个有趣的文档,可以帮助您了解数字签名的必要性。