Search in sources :

Example 16 with Signature

use of com.github.zhenwei.core.asn1.ocsp.Signature in project LinLong-Java by zhenwei1108.

the class SignatureSpi method engineVerify.

protected boolean engineVerify(byte[] sigBytes) throws SignatureException {
    byte[] hash = new byte[digest.getDigestSize()];
    digest.doFinal(hash, 0);
    BigInteger[] sig;
    try {
        byte[] bytes = ((ASN1OctetString) ASN1OctetString.fromByteArray(sigBytes)).getOctets();
        byte[] r = new byte[bytes.length / 2];
        byte[] s = new byte[bytes.length / 2];
        System.arraycopy(bytes, 0, s, 0, bytes.length / 2);
        System.arraycopy(bytes, bytes.length / 2, r, 0, bytes.length / 2);
        sig = new BigInteger[2];
        sig[0] = new BigInteger(1, r);
        sig[1] = new BigInteger(1, s);
    } catch (Exception e) {
        throw new SignatureException("error decoding signature bytes.");
    }
    return signer.verifySignature(hash, sig[0], sig[1]);
}
Also used : ASN1OctetString(com.github.zhenwei.core.asn1.ASN1OctetString) BigInteger(java.math.BigInteger) SignatureException(java.security.SignatureException) SignatureException(java.security.SignatureException) InvalidKeyException(java.security.InvalidKeyException)

Example 17 with Signature

use of com.github.zhenwei.core.asn1.ocsp.Signature in project LinLong-Java by zhenwei1108.

the class SignatureSpiLe method engineSign.

protected byte[] engineSign() throws SignatureException {
    byte[] signature = ASN1OctetString.getInstance(super.engineSign()).getOctets();
    reverseBytes(signature);
    try {
        return (new DEROctetString(signature)).getEncoded();
    } catch (Exception e) {
        throw new SignatureException(e.toString());
    }
}
Also used : SignatureException(java.security.SignatureException) DEROctetString(com.github.zhenwei.core.asn1.DEROctetString) SignatureException(java.security.SignatureException) IOException(java.io.IOException)

Example 18 with Signature

use of com.github.zhenwei.core.asn1.ocsp.Signature in project LinLong-Java by zhenwei1108.

the class Signature method getInstance.

public static Signature getInstance(Object objectAt) {
    if (objectAt instanceof Signature) {
        return (Signature) objectAt;
    }
    ASN1TaggedObject ato = ASN1TaggedObject.getInstance(objectAt);
    ASN1Encodable value;
    switch(ato.getTagNo()) {
        case ecdsaNistP256Signature:
        case ecdsaBrainpoolP256r1Signature:
            value = EcdsaP256Signature.getInstance(ato.getObject());
            break;
        case extension:
            value = DEROctetString.getInstance(ato.getObject());
            break;
        case ecdsaBrainpoolP384r1Signature:
            value = EcdsaP384Signature.getInstance(ato.getObject());
            break;
        default:
            throw new IllegalStateException("unknown choice " + ato.getTagNo());
    }
    return new Signature(ato.getTagNo(), value);
}
Also used : ASN1TaggedObject(com.github.zhenwei.core.asn1.ASN1TaggedObject) ASN1Encodable(com.github.zhenwei.core.asn1.ASN1Encodable)

Example 19 with Signature

use of com.github.zhenwei.core.asn1.ocsp.Signature in project LinLong-Java by zhenwei1108.

the class BcFKSKeyStoreSpi method engineLoad.

public void engineLoad(InputStream inputStream, char[] password) throws IOException, NoSuchAlgorithmException, CertificateException {
    // reset any current values
    entries.clear();
    privateKeyCache.clear();
    lastModifiedDate = creationDate = null;
    hmacAlgorithm = null;
    if (inputStream == null) {
        // initialise defaults
        lastModifiedDate = creationDate = new Date();
        verificationKey = null;
        validator = null;
        // basic initialisation
        hmacAlgorithm = new AlgorithmIdentifier(PKCSObjectIdentifiers.id_hmacWithSHA512, DERNull.INSTANCE);
        hmacPkbdAlgorithm = generatePkbdAlgorithmIdentifier(PKCSObjectIdentifiers.id_PBKDF2, 512 / 8);
        return;
    }
    ASN1InputStream aIn = new ASN1InputStream(inputStream);
    ObjectStore store;
    try {
        store = ObjectStore.getInstance(aIn.readObject());
    } catch (Exception e) {
        throw new IOException(e.getMessage());
    }
    ObjectStoreIntegrityCheck integrityCheck = store.getIntegrityCheck();
    AlgorithmIdentifier integrityAlg;
    if (integrityCheck.getType() == ObjectStoreIntegrityCheck.PBKD_MAC_CHECK) {
        PbkdMacIntegrityCheck pbkdMacIntegrityCheck = PbkdMacIntegrityCheck.getInstance(integrityCheck.getIntegrityCheck());
        hmacAlgorithm = pbkdMacIntegrityCheck.getMacAlgorithm();
        hmacPkbdAlgorithm = pbkdMacIntegrityCheck.getPbkdAlgorithm();
        integrityAlg = hmacAlgorithm;
        try {
            verifyMac(store.getStoreData().toASN1Primitive().getEncoded(), pbkdMacIntegrityCheck, password);
        } catch (NoSuchProviderException e) {
            throw new IOException(e.getMessage());
        }
    } else if (integrityCheck.getType() == ObjectStoreIntegrityCheck.SIG_CHECK) {
        SignatureCheck sigCheck = SignatureCheck.getInstance(integrityCheck.getIntegrityCheck());
        integrityAlg = sigCheck.getSignatureAlgorithm();
        try {
            com.github.zhenwei.core.asn1.x509.Certificate[] certificates = sigCheck.getCertificates();
            if (validator != null) {
                if (certificates == null) {
                    throw new IOException("validator specified but no certifcates in store");
                }
                CertificateFactory certFact = helper.createCertificateFactory("X.509");
                X509Certificate[] certs = new X509Certificate[certificates.length];
                for (int i = 0; i != certs.length; i++) {
                    certs[i] = (X509Certificate) certFact.generateCertificate(new ByteArrayInputStream(certificates[i].getEncoded()));
                }
                if (validator.isValid(certs)) {
                    verifySig(store.getStoreData(), sigCheck, certs[0].getPublicKey());
                } else {
                    throw new IOException("certificate chain in key store signature not valid");
                }
            } else {
                verifySig(store.getStoreData(), sigCheck, verificationKey);
            }
        } catch (GeneralSecurityException e) {
            throw new IOException("error verifying signature: " + e.getMessage(), e);
        }
    } else {
        throw new IOException("BCFKS KeyStore unable to recognize integrity check.");
    }
    ASN1Encodable sData = store.getStoreData();
    ObjectStoreData storeData;
    if (sData instanceof EncryptedObjectStoreData) {
        EncryptedObjectStoreData encryptedStoreData = (EncryptedObjectStoreData) sData;
        AlgorithmIdentifier protectAlgId = encryptedStoreData.getEncryptionAlgorithm();
        storeData = ObjectStoreData.getInstance(decryptData("STORE_ENCRYPTION", protectAlgId, password, encryptedStoreData.getEncryptedContent().getOctets()));
    } else {
        storeData = ObjectStoreData.getInstance(sData);
    }
    try {
        creationDate = storeData.getCreationDate().getDate();
        lastModifiedDate = storeData.getLastModifiedDate().getDate();
    } catch (ParseException e) {
        throw new IOException("BCFKS KeyStore unable to parse store data information.");
    }
    if (!storeData.getIntegrityAlgorithm().equals(integrityAlg)) {
        throw new IOException("BCFKS KeyStore storeData integrity algorithm does not match store integrity algorithm.");
    }
    for (Iterator it = storeData.getObjectDataSequence().iterator(); it.hasNext(); ) {
        ObjectData objData = ObjectData.getInstance(it.next());
        entries.put(objData.getIdentifier(), objData);
    }
}
Also used : PbkdMacIntegrityCheck(com.github.zhenwei.core.asn1.bc.PbkdMacIntegrityCheck) ASN1InputStream(com.github.zhenwei.core.asn1.ASN1InputStream) ObjectStore(com.github.zhenwei.core.asn1.bc.ObjectStore) GeneralSecurityException(java.security.GeneralSecurityException) ObjectData(com.github.zhenwei.core.asn1.bc.ObjectData) IOException(java.io.IOException) EncryptedObjectStoreData(com.github.zhenwei.core.asn1.bc.EncryptedObjectStoreData) CertificateFactory(java.security.cert.CertificateFactory) Date(java.util.Date) KeyStoreException(java.security.KeyStoreException) GeneralSecurityException(java.security.GeneralSecurityException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) CertificateEncodingException(java.security.cert.CertificateEncodingException) IOException(java.io.IOException) ParseException(java.text.ParseException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) CertificateException(java.security.cert.CertificateException) BadPaddingException(javax.crypto.BadPaddingException) NoSuchProviderException(java.security.NoSuchProviderException) X509Certificate(java.security.cert.X509Certificate) AlgorithmIdentifier(com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier) SignatureCheck(com.github.zhenwei.core.asn1.bc.SignatureCheck) ByteArrayInputStream(java.io.ByteArrayInputStream) Iterator(java.util.Iterator) ASN1Encodable(com.github.zhenwei.core.asn1.ASN1Encodable) ParseException(java.text.ParseException) NoSuchProviderException(java.security.NoSuchProviderException) ObjectStoreData(com.github.zhenwei.core.asn1.bc.ObjectStoreData) EncryptedObjectStoreData(com.github.zhenwei.core.asn1.bc.EncryptedObjectStoreData) ObjectStoreIntegrityCheck(com.github.zhenwei.core.asn1.bc.ObjectStoreIntegrityCheck)

Example 20 with Signature

use of com.github.zhenwei.core.asn1.ocsp.Signature in project LinLong-Java by zhenwei1108.

the class ProvOcspRevocationChecker method validatedOcspResponse.

static boolean validatedOcspResponse(BasicOCSPResponse basicResp, PKIXCertRevocationCheckerParameters parameters, byte[] nonce, X509Certificate responderCert, JcaJceHelper helper) throws CertPathValidatorException {
    try {
        ASN1Sequence certs = basicResp.getCerts();
        Signature sig = helper.createSignature(getSignatureName(basicResp.getSignatureAlgorithm()));
        X509Certificate sigCert = getSignerCert(basicResp, parameters.getSigningCert(), responderCert, helper);
        if (sigCert == null && certs == null) {
            throw new CertPathValidatorException("OCSP responder certificate not found");
        }
        if (sigCert != null) {
            sig.initVerify(sigCert.getPublicKey());
        } else {
            CertificateFactory cf = helper.createCertificateFactory("X.509");
            X509Certificate ocspCert = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(certs.getObjectAt(0).toASN1Primitive().getEncoded()));
            // check cert signed by CA
            ocspCert.verify(parameters.getSigningCert().getPublicKey());
            // check cert valid
            ocspCert.checkValidity(parameters.getValidDate());
            // check ID
            if (!responderMatches(basicResp.getTbsResponseData().getResponderID(), ocspCert, helper)) {
                throw new CertPathValidatorException("responder certificate does not match responderID", null, parameters.getCertPath(), parameters.getIndex());
            }
            // TODO: RFC 6960 allows for a "no check" extension - where present it means the CA says the cert
            // will remain valid for it's lifetime. If any caching is added here that should be taken into account.
            // check we are valid
            List extendedKeyUsage = ocspCert.getExtendedKeyUsage();
            if (extendedKeyUsage == null || !extendedKeyUsage.contains(KeyPurposeId.id_kp_OCSPSigning.getId())) {
                throw new CertPathValidatorException("responder certificate not valid for signing OCSP responses", null, parameters.getCertPath(), parameters.getIndex());
            }
            sig.initVerify(ocspCert);
        }
        sig.update(basicResp.getTbsResponseData().getEncoded(ASN1Encoding.DER));
        if (sig.verify(basicResp.getSignature().getBytes())) {
            if (nonce != null) {
                Extensions exts = basicResp.getTbsResponseData().getResponseExtensions();
                com.github.zhenwei.core.asn1.x509.Extension ext = exts.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce);
                if (!Arrays.areEqual(nonce, ext.getExtnValue().getOctets())) {
                    throw new CertPathValidatorException("nonce mismatch in OCSP response", null, parameters.getCertPath(), parameters.getIndex());
                }
            }
            return true;
        }
        return false;
    } catch (CertPathValidatorException e) {
        throw e;
    } catch (GeneralSecurityException e) {
        throw new CertPathValidatorException("OCSP response failure: " + e.getMessage(), e, parameters.getCertPath(), parameters.getIndex());
    } catch (IOException e) {
        throw new CertPathValidatorException("OCSP response failure: " + e.getMessage(), e, parameters.getCertPath(), parameters.getIndex());
    }
}
Also used : GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) Extensions(com.github.zhenwei.core.asn1.x509.Extensions) CertificateFactory(java.security.cert.CertificateFactory) X509Certificate(java.security.cert.X509Certificate) CertPathValidatorException(java.security.cert.CertPathValidatorException) ExtCertPathValidatorException(com.github.zhenwei.provider.jce.exception.ExtCertPathValidatorException) ASN1Sequence(com.github.zhenwei.core.asn1.ASN1Sequence) ByteArrayInputStream(java.io.ByteArrayInputStream) Signature(java.security.Signature) List(java.util.List)

Aggregations

IOException (java.io.IOException)44 ASN1EncodableVector (com.github.zhenwei.core.asn1.ASN1EncodableVector)34 DERSequence (com.github.zhenwei.core.asn1.DERSequence)29 DERBitString (com.github.zhenwei.core.asn1.DERBitString)21 AlgorithmIdentifier (com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier)20 OutputStream (java.io.OutputStream)20 SignatureException (java.security.SignatureException)20 GeneralSecurityException (java.security.GeneralSecurityException)15 Signature (java.security.Signature)15 ASN1ObjectIdentifier (com.github.zhenwei.core.asn1.ASN1ObjectIdentifier)14 DEROctetString (com.github.zhenwei.core.asn1.DEROctetString)14 InvalidKeyException (java.security.InvalidKeyException)13 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)13 Iterator (java.util.Iterator)13 OperatorCreationException (com.github.zhenwei.pkix.operator.OperatorCreationException)11 CertificateEncodingException (java.security.cert.CertificateEncodingException)11 NoSuchProviderException (java.security.NoSuchProviderException)10 ASN1OctetString (com.github.zhenwei.core.asn1.ASN1OctetString)9 ASN1Sequence (com.github.zhenwei.core.asn1.ASN1Sequence)9 List (java.util.List)9