如何将OpenSSL数字签名转换为ASN1?

时间:2016-10-25 18:47:26

标签: java openssl rsa digital-signature asn.1

使用openssl库我创建了一个文件的数字签名。

我可以看到,如果我使用openssl命令:

openssl rsautl -verify -inkey pubkey.pem -pubin -asn1parse -in sigfile

我得到了一个很好的输出:

0:d=0  hl=2 l=  49 cons: SEQUENCE          
2:d=1  hl=2 l=  13 cons:  SEQUENCE          
4:d=2  hl=2 l=   9 prim:   OBJECT            :sha256
15:d=2  hl=2 l=   0 prim:   NULL              
17:d=1  hl=2 l=  32 prim:  OCTET STRING      
  0000 - c9 8c 24 b6 77 ef f4 48-60 af ea 6f 49 3b ba ec   ..$.w..H`..oI;..
  0010 - 5b b1 c4 cb b2 09 c6 fc-2b bb 47 f6 6f f2 ad 31   [.......+.G.o..1

如何以编程方式将我的签名文件转换为一些我可以解析的ASN1?

2 个答案:

答案 0 :(得分:0)

OpenSSL signedData ::= SEQUENCE { version Version, digestAlgorithms DigestAlgorithmIdentifiers, contentInfo ContentInfo, certificates [0] IMPLICIT ExtendedCertificatesAndCertificates OPTIONAL, crls [1] IMPLICIT CertificateRevocationLists OPTIONAL, signerInfos SignerInfos } 命令输出RSA签名的恢复数据

  

-verify        验证输入数据并输出恢复的数据。

这意味着返回PKCS#1消息。 RFC2313之后的数字签名由摘要算法标识符和内容的加密摘要以及PKC#7格式的RSA私钥组成,如RFC2315的9.1节所述。

public class ASN1Decoder {
    private static String opensslOutputB64= "MDEwDQYJYIZIAWUDBAIBBQAEIGGbJmsmf9lg/jeaXjm0XsUZ4ZS7xv0Da/NvPoNiRzRO";

    public final static void main(String argv[]) throws IOException{
        ASN1InputStream bIn = new ASN1InputStream(new ByteArrayInputStream(Base64.getDecoder().decode(opensslOutputB64)));
         ASN1Primitive obj = bIn.readObject();
         System.out.println(ASN1Dump.dumpAsString(obj));

    }
}

所以(如果我理解正确的话......), openssl的输出是一个ASN.1序列的摘要算法+解密摘要(你内容的原始摘要)

要对其进行解码,您可以使用Bouncycastle

data have;
  input id x y z;
datalines;
1 1 . .
1 . 2 .
1 . . 3
2 4 . .
2 . 5 .
2 . . 6
;;;;
run;

data want;
  update have(obs=0) have;
  by id;
run;

查看Parsing ASN.1 binary data with Java了解更多示例

答案 1 :(得分:0)

在@pedrofb的帮助下,我设法提出了以下解决方案:

// Get key from cert
CertificateFactory fact = CertificateFactory.getInstance("X.509", new org.bouncycastle.jce.provider.BouncyCastleProvider());
X509Certificate cer = (X509Certificate) fact.generateCertificate(new FileInputStream("/home/administrator/Downloads/cert_1.txt"));
PublicKey key = cer.getPublicKey();

// or read key in from pem file
PublicKey publicKey = ManifestUtils.publicKeyFromPemFile(new FileReader("/home/administrator/Downloads/publickey.txt"));

// Decrypt the signature
Cipher asymmetricCipher
            = Cipher.getInstance("RSA/ECB/PKCS1Padding", new org.bouncycastle.jce.provider.BouncyCastleProvider());
asymmetricCipher.init(Cipher.DECRYPT_MODE, publicKey);
byte[] plainText = asymmetricCipher.doFinal(
            IOUtils.toByteArray(new FileInputStream("/home/administrator/Downloads/signature.sign")));

// print as hex
System.out.println(Hex.encodeHexString(plainText));

// Print the ans1 nicely - ish
ASN1InputStream input = new ASN1InputStream(plainText);
ASN1Primitive p;
while ((p = input.readObject()) != null) {
    System.out.println(ASN1Dump.dumpAsString(p));
}