Daria Bulanova
Daria Bulanova

Reputation: 577

How to verify xmldsig signature using java.security

I need to verify document with enveloped xml-dsig signature using java.security package. After loading I unmarshal document and have object of Signature according to xsd - http://www.w3.org/2000/09/xmldsig#

Then:

@Service
public class XmlSignatureCheckerImpl implements XmlSignatureChecker {
    private static final String ENCRYPTION_ALGORITHM = "RSA";

    private static final String HASH_ENCRYPTION_ALGORITHM = "SHA1withRSA";

    @Override
    @Nullable
    public PublicKey getPublicKey(byte[] exp, byte[] mod) {
        BigInteger modulus = new BigInteger(1, mod);
        BigInteger exponent = new BigInteger(1, exp);
        RSAPublicKeySpec rsaPubKey = new RSAPublicKeySpec(modulus, exponent);

        KeyFactory fact;
        try {
            fact = KeyFactory.getInstance(ENCRYPTION_ALGORITHM);
            return fact.generatePublic(rsaPubKey);
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    @Nullable
    public Boolean verify(byte[] message, byte[] signature, PublicKey publicKey) {
        final Signature sig;
        try {
            sig = Signature.getInstance(HASH_ENCRYPTION_ALGORITHM);
            sig.initVerify(publicKey);
            sig.update(message);
            boolean verify = sig.verify(Base64.encodeBase64Chunked(signature));
            return verify;
        } catch (NoSuchAlgorithmException | SignatureException | InvalidKeyException e) {
            e.printStackTrace();
        }
        return null;
    }
}

Call getPublicKey and verify, as a result I got signature length mismatch, if I did't encode signature I got no mismatch, but also verification is false, but I use test data which is completely valid. Give up with finding error, help me. please. File encoding is UFT-8.

Upvotes: 4

Views: 1619

Answers (1)

DouglasD
DouglasD

Reputation: 48

Have you look at official documentation? Seems like working with the sign factory is a bit more convenient http://www.oracle.com/technetwork/articles/javase/dig-signature-api-140772.html

Also, I've found these examples if it will be helpful https://www.java-tips.org/java-ee-tips-100042/158-xml-digital-signature-api/1473-using-the-java-xml-digital-signature-api.html

Upvotes: 1

Related Questions