验证Android上的数字签名

时间:2015-12-03 13:11:06

标签: java android json digital-signature

我正在开发一个需要数字签名html文档的Android应用程序。 该文档以JSON格式驻留在DB中。 我正在使用我在其他一些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 

公钥是使用以下方式生成的:

openssl pkey -in privateKey.pem -out publicKey.pem -pubout

我想在应用程序中验证Signature.bin中创建的签名以及someHTMLDoc.html中的数据。

我发送的html和签名为JSON Object ex:

{ "data" : "<html><body></body></html>", "signature":"6598 13a9 b12b 21a9 ..... " }

android应用程序将PublicKey保存在共享首选项中,如下所示:

-----BEGIN PUBLIC KEY----- MIIBIDANBgkqhkiG9w0AAAEFAAOCAQ0AvniCAKCAQEAvni/NSEX3Rhx91HkJl85 \nx1noyYET ......

  

请注意“\ n”(换行符)(从publicKey.pem复制字符串到Android Gradle配置时自动添加。

好的,经过一切准备,现在的问题。 我试图验证密钥没有成功。

我使用以下代码:

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文件中?

提前感谢所有帮助,非常感谢。

2 个答案:

答案 0 :(得分:4)

数字签名是计算数据(C)的摘要(函数H)并使用非对称加密算法(函数E)对其进行加密以生成密文(S)的过程:

S = E(H(C))

签名验证使签名解密给定签名(函数D) - 仅当解密中使用的公钥与加密中使用的私钥配对时才导致H(C),并计算数据的摘要以检查是否两个摘要匹配:

H(C) == D(E(H(C)))

由此可以清楚地看出,为了使签名得到验证,给予散列函数(C)的字节必须完全相同。

在你的情况下它们不是,因为当你使用openssl dgst计算摘要时,输出(右边的H(C))实际上是这样的:

SHA1(someHTMLDoc.html)= 22596363b3de40b06f981fb85d82312e8c0ed511

这是RSA加密的输入。

当你验证签名时,摘要的输出(左边是H(C))是原始字节,例如十六进制:

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                                ....

此外,您需要将-signopenssl 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对公钥进行PEM解码,使事情更具可读性和易用性。

答案 1 :(得分:1)

如果您有一个经过数字签名的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 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;

    }

原因是,如果您在android studio中使用相同的代码,则需要添加依赖项,有时还会造成混淆。

如果您有兴趣阅读数字签名文档,可以阅读www.xml.com/post。这是一个有趣的文档,可帮助您理解数字签名的必要性。