Example usage for java.security Signature getInstance

List of usage examples for java.security Signature getInstance

Introduction

In this page you can find the example usage for java.security Signature getInstance.

Prototype

public static Signature getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a Signature object that implements the specified signature algorithm.

Usage

From source file:org.atricore.idbus.capabilities.sso.support.core.signature.JSR105SamlR2SignerImpl.java

public String signQueryString(String queryString) throws SamlR2SignatureException {

    try {/*from  w w  w . j  a v  a  2  s  .  co m*/

        if (queryString == null || queryString.length() == 0) {
            logger.error("SAML 2.0 Qery string null");
            throw new SamlR2SignatureException("SAML 2.0 Qery string null");
        }

        if (logger.isDebugEnabled())
            logger.debug("Received SAML 2.0 Query string [" + queryString + "] for signing");

        PrivateKey privateKey = (PrivateKey) this.getKeyResolver().getPrivateKey();

        String keyAlgorithm = privateKey.getAlgorithm();
        Signature signature = null;
        String algURI = null;
        if (keyAlgorithm.equals("RSA")) {
            signature = Signature.getInstance(SHA1_WITH_RSA);
            algURI = SignatureMethod.RSA_SHA1;
        } else if (keyAlgorithm.equals("DSA")) {
            signature = Signature.getInstance(SHA1_WITH_DSA);
            algURI = SignatureMethod.DSA_SHA1;
        } else {
            throw new SamlR2SignatureException(
                    "SAML 2.0 Signature does not support provided key's algorithm " + keyAlgorithm);
        }

        if (queryString.charAt(queryString.length() - 1) != '&') {
            queryString = queryString + "&";
        }

        queryString += "SigAlg=" + URLEncoder.encode(algURI, "UTF-8");

        if (logger.isTraceEnabled())
            logger.trace("Signing SAML 2.0 Query string [" + queryString + "]");

        signature.initSign(privateKey);
        signature.update(queryString.getBytes());
        byte[] sigBytes = null;
        sigBytes = signature.sign();
        if (sigBytes == null || sigBytes.length == 0) {
            logger.error("Cannot generate signed query string, Signature created 'null' value.");
            throw new SamlR2SignatureException(
                    "Cannot generate signed query string, Signature created 'null' value.");
        }

        Base64 encoder = new Base64();
        String encodedSig = new String(encoder.encode(sigBytes), "UTF-8");
        queryString += "&Signature=" + URLEncoder.encode(encodedSig, "UTF-8");

        if (logger.isTraceEnabled())
            logger.trace("Signed SAML 2.0 Query string [" + queryString + "]");

        return queryString;
    } catch (Exception e) {
        throw new SamlR2SignatureException("Error generating SAML 2.0 Query string signature " + e.getMessage(),
                e);
    }
}

From source file:org.apache.cxf.fediz.service.idp.protocols.TrustedIdpSAMLProtocolHandler.java

/**
 * Sign a request according to the redirect binding spec for Web SSO
 *//*  www  . j av a2s. c  om*/
private void signRequest(String authnRequest, String relayState, Idp config, UriBuilder ub) throws Exception {
    Crypto crypto = getCrypto(config.getCertificate());
    if (crypto == null) {
        LOG.error("No crypto instance of properties file configured for signature");
        throw new IllegalStateException("Invalid IdP configuration");
    }

    String alias = crypto.getDefaultX509Identifier();
    X509Certificate cert = CertsUtils.getX509Certificate(crypto, alias);
    if (cert == null) {
        LOG.error("No cert was found to sign the request using alias: " + alias);
        throw new IllegalStateException("Invalid IdP configuration");
    }

    String sigAlgo = SSOConstants.RSA_SHA1;
    String pubKeyAlgo = cert.getPublicKey().getAlgorithm();
    String jceSigAlgo = "SHA1withRSA";
    LOG.debug("automatic sig algo detection: " + pubKeyAlgo);
    if (pubKeyAlgo.equalsIgnoreCase("DSA")) {
        sigAlgo = SSOConstants.DSA_SHA1;
        jceSigAlgo = "SHA1withDSA";
    }
    LOG.debug("Using Signature algorithm " + sigAlgo);

    ub.queryParam(SSOConstants.SIG_ALG, URLEncoder.encode(sigAlgo, "UTF-8"));

    // Get the password
    String password = config.getCertificatePassword();

    // Get the private key
    PrivateKey privateKey = crypto.getPrivateKey(alias, password);

    // Sign the request
    Signature signature = Signature.getInstance(jceSigAlgo);
    signature.initSign(privateKey);

    String requestToSign = SSOConstants.SAML_REQUEST + "=" + authnRequest + "&" + SSOConstants.RELAY_STATE + "="
            + relayState + "&" + SSOConstants.SIG_ALG + "=" + URLEncoder.encode(sigAlgo, "UTF-8");

    signature.update(requestToSign.getBytes("UTF-8"));
    byte[] signBytes = signature.sign();

    String encodedSignature = Base64.encode(signBytes);

    ub.queryParam(SSOConstants.SIGNATURE, URLEncoder.encode(encodedSignature, "UTF-8"));
}

From source file:nl.b3p.viewer.stripes.CycloramaActionBean.java

private byte[] sign(PrivateKey privateKey, String token)
        throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {

    Signature instance = Signature.getInstance(SIG_ALGORITHM);
    instance.initSign(privateKey);/*from  w  w  w. ja v a 2 s. c o m*/
    instance.update(token.getBytes());
    byte[] signature = instance.sign();

    return signature;
}

From source file:org.ejbca.ui.cmpclient.commands.KeyUpdateRequestCommand.java

@Override
public PKIMessage generatePKIMessage(ParameterContainer parameters) throws Exception {
    boolean verbose = parameters.containsKey(VERBOSE_KEY);

    final X500Name userDN = new X500Name(parameters.get(SUBJECTDN_KEY));
    final X500Name issuerDN = new X500Name(parameters.get(ISSUERDN_KEY));
    boolean includePopo = parameters.containsKey(INCLUDE_POPO_KEY);

    if (verbose) {
        log.info("Creating KeyUpdate request with: SubjectDN=" + userDN.toString());
        log.info("Creating KeyUpdate request with: IssuerDN=" + issuerDN.toString());
        log.info("Creating KeyUpdate request with: IncludePopo=" + includePopo);
    }// ww w . j  av  a 2s  .co m

    byte[] nonce = CmpClientMessageHelper.getInstance().createSenderNonce();
    byte[] transid = CmpClientMessageHelper.getInstance().createSenderNonce();
    KeyPair keys = KeyTools.genKeys("1024", AlgorithmConstants.KEYALGORITHM_RSA);

    CertTemplateBuilder myCertTemplate = new CertTemplateBuilder();

    ASN1EncodableVector optionalValidityV = new ASN1EncodableVector();
    org.bouncycastle.asn1.x509.Time nb = new org.bouncycastle.asn1.x509.Time(
            new DERGeneralizedTime("20030211002120Z"));
    org.bouncycastle.asn1.x509.Time na = new org.bouncycastle.asn1.x509.Time(new Date());
    optionalValidityV.add(new DERTaggedObject(true, 0, nb));
    optionalValidityV.add(new DERTaggedObject(true, 1, na));
    OptionalValidity myOptionalValidity = OptionalValidity.getInstance(new DERSequence(optionalValidityV));

    myCertTemplate.setValidity(myOptionalValidity);

    byte[] bytes = keys.getPublic().getEncoded();
    ByteArrayInputStream bIn = new ByteArrayInputStream(bytes);
    ASN1InputStream dIn = new ASN1InputStream(bIn);
    try {
        SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo((ASN1Sequence) dIn.readObject());
        myCertTemplate.setPublicKey(keyInfo);
    } finally {
        dIn.close();
    }

    myCertTemplate.setSubject(userDN);

    CertRequest myCertRequest = new CertRequest(4, myCertTemplate.build(), null);

    // POPO
    /*
     * PKMACValue myPKMACValue = new PKMACValue( new AlgorithmIdentifier(new
     * ASN1ObjectIdentifier("8.2.1.2.3.4"), new DERBitString(new byte[] { 8,
     * 1, 1, 2 })), new DERBitString(new byte[] { 12, 29, 37, 43 }));
     * 
     * POPOPrivKey myPOPOPrivKey = new POPOPrivKey(new DERBitString(new
     * byte[] { 44 }), 2); //take choice pos tag 2
     * 
     * POPOSigningKeyInput myPOPOSigningKeyInput = new POPOSigningKeyInput(
     * myPKMACValue, new SubjectPublicKeyInfo( new AlgorithmIdentifier(new
     * ASN1ObjectIdentifier("9.3.3.9.2.2"), new DERBitString(new byte[] { 2,
     * 9, 7, 3 })), new byte[] { 7, 7, 7, 4, 5, 6, 7, 7, 7 }));
     */
    ProofOfPossession myProofOfPossession = null;
    if (includePopo) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DEROutputStream mout = new DEROutputStream(baos);
        mout.writeObject(myCertRequest);
        mout.close();
        byte[] popoProtectionBytes = baos.toByteArray();
        String sigalg = AlgorithmTools.getSignAlgOidFromDigestAndKey(null, keys.getPrivate().getAlgorithm())
                .getId();
        Signature sig = Signature.getInstance(sigalg);
        sig.initSign(keys.getPrivate());
        sig.update(popoProtectionBytes);

        DERBitString bs = new DERBitString(sig.sign());

        POPOSigningKey myPOPOSigningKey = new POPOSigningKey(null,
                new AlgorithmIdentifier(new ASN1ObjectIdentifier(sigalg)), bs);
        myProofOfPossession = new ProofOfPossession(myPOPOSigningKey);
    } else {
        // raVerified POPO (meaning there is no POPO)
        myProofOfPossession = new ProofOfPossession();
    }

    // myCertReqMsg.addRegInfo(new AttributeTypeAndValue(new
    // ASN1ObjectIdentifier("1.3.6.2.2.2.2.3.1"), new
    // DERInteger(1122334455)));
    AttributeTypeAndValue av = new AttributeTypeAndValue(CRMFObjectIdentifiers.id_regCtrl_regToken,
            new DERUTF8String(""));
    AttributeTypeAndValue[] avs = { av };

    CertReqMsg myCertReqMsg = new CertReqMsg(myCertRequest, myProofOfPossession, avs);

    CertReqMessages myCertReqMessages = new CertReqMessages(myCertReqMsg);

    PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(userDN), new GeneralName(issuerDN));
    myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date()));
    // senderNonce
    myPKIHeader.setSenderNonce(new DEROctetString(nonce));
    // TransactionId
    myPKIHeader.setTransactionID(new DEROctetString(transid));
    myPKIHeader.setProtectionAlg(null);

    PKIBody myPKIBody = new PKIBody(PKIBody.TYPE_KEY_UPDATE_REQ, myCertReqMessages); // Key Update Request
    PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);

    return myPKIMessage;
}

From source file:org.wso2.carbon.apimgt.keymgt.token.AbstractJWTGenerator.java

private byte[] signJWT(String assertion, String endUserName) throws APIManagementException {

    String tenantDomain = null;//w  ww .  ja  v  a2  s  .  c  o  m

    try {
        //get tenant domain
        tenantDomain = MultitenantUtils.getTenantDomain(endUserName);
        //get tenantId
        int tenantId = APIUtil.getTenantId(endUserName);

        Key privateKey = null;

        if (!(privateKeys.containsKey(tenantId))) {
            APIUtil.loadTenantRegistry(tenantId);
            //get tenant's key store manager
            KeyStoreManager tenantKSM = KeyStoreManager.getInstance(tenantId);

            if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
                //derive key store name
                String ksName = tenantDomain.trim().replace('.', '-');
                String jksName = ksName + ".jks";
                //obtain private key
                //TODO: maintain a hash map with tenants' private keys after first initialization
                privateKey = tenantKSM.getPrivateKey(jksName, tenantDomain);
            } else {
                try {
                    privateKey = tenantKSM.getDefaultPrivateKey();
                } catch (Exception e) {
                    log.error("Error while obtaining private key for super tenant", e);
                }
            }
            if (privateKey != null) {
                privateKeys.put(tenantId, privateKey);
            }
        } else {
            privateKey = privateKeys.get(tenantId);
        }

        //initialize signature with private key and algorithm
        Signature signature = Signature.getInstance(signatureAlgorithm);
        signature.initSign((PrivateKey) privateKey);

        //update signature with data to be signed
        byte[] dataInBytes = assertion.getBytes(Charset.defaultCharset());
        signature.update(dataInBytes);

        //sign the assertion and return the signature
        return signature.sign();

    } catch (NoSuchAlgorithmException e) {
        String error = "Signature algorithm not found.";
        //do not log
        throw new APIManagementException(error, e);
    } catch (InvalidKeyException e) {
        String error = "Invalid private key provided for the signature";
        //do not log
        throw new APIManagementException(error, e);
    } catch (SignatureException e) {
        String error = "Error in signature";
        //do not log
        throw new APIManagementException(error, e);
    } catch (RegistryException e) {
        String error = "Error in loading tenant registry for " + tenantDomain;
        //do not log
        throw new APIManagementException(error, e);
    }
}

From source file:com.blackducksoftware.integration.hub.jenkins.site.BlackDuckHubUpdateSite.java

/**
 * Verifies the signature in the update center data file.
 *//*from  w w w  .j a  v a2  s . c  om*/
private FormValidation verifySignature(final JSONObject o) throws IOException {
    try {
        FormValidation warning = null;

        final JSONObject signature = o.getJSONObject("signature");
        if (signature.isNullObject()) {
            return FormValidation.error("No signature block found in update center '" + getId() + "'");
        }
        o.remove("signature");

        final List<X509Certificate> certs = new ArrayList<X509Certificate>();
        {// load and verify certificates
            final CertificateFactory cf = CertificateFactory.getInstance("X509");
            for (final Object cert : signature.getJSONArray("certificates")) {
                final X509Certificate c = (X509Certificate) cf.generateCertificate(
                        new ByteArrayInputStream(Base64.decode(cert.toString().toCharArray())));
                try {
                    c.checkValidity();
                } catch (final CertificateExpiredException e) { // even if the certificate isn't valid yet,
                    // we'll proceed it anyway
                    warning = FormValidation.warning(e, String.format(
                            "Certificate %s has expired in update center '%s'", cert.toString(), getId()));
                } catch (final CertificateNotYetValidException e) {
                    warning = FormValidation.warning(e, String.format(
                            "Certificate %s is not yet valid in update center '%s'", cert.toString(), getId()));
                }
                certs.add(c);
            }

            // all default root CAs in JVM are trusted, plus certs bundled in Jenkins
            final Set<TrustAnchor> anchors = new HashSet<TrustAnchor>(); // CertificateUtil.getDefaultRootCAs();
            final ServletContext context = Jenkins.getInstance().servletContext;
            anchors.add(new TrustAnchor(loadLicenseCaCertificate(), null));
            for (final String cert : (Set<String>) context.getResourcePaths("/WEB-INF/update-center-rootCAs")) {
                if (cert.endsWith(".txt")) {
                    continue; // skip text files that are meant to be documentation
                }
                final InputStream stream = context.getResourceAsStream(cert);
                if (stream != null) {
                    try {
                        anchors.add(new TrustAnchor((X509Certificate) cf.generateCertificate(stream), null));
                    } finally {
                        IOUtils.closeQuietly(stream);
                    }
                }
            }
            CertificateUtil.validatePath(certs, anchors);
        }

        // this is for computing a digest to check sanity
        final MessageDigest sha1 = MessageDigest.getInstance("SHA1");
        final DigestOutputStream dos = new DigestOutputStream(new NullOutputStream(), sha1);

        // this is for computing a signature
        final Signature sig = Signature.getInstance("SHA1withRSA");
        sig.initVerify(certs.get(0));
        final SignatureOutputStream sos = new SignatureOutputStream(sig);

        // until JENKINS-11110 fix, UC used to serve invalid digest (and therefore unverifiable signature)
        // that only covers the earlier portion of the file. This was caused by the lack of close() call
        // in the canonical writing, which apparently leave some bytes somewhere that's not flushed to
        // the digest output stream. This affects Jenkins [1.424,1,431].
        // Jenkins 1.432 shipped with the "fix" (1eb0c64abb3794edce29cbb1de50c93fa03a8229) that made it
        // compute the correct digest, but it breaks all the existing UC json metadata out there. We then
        // quickly discovered ourselves in the catch-22 situation. If we generate UC with the correct signature,
        // it'll cut off [1.424,1.431] from the UC. But if we don't, we'll cut off [1.432,*).
        //
        // In 1.433, we revisited 1eb0c64abb3794edce29cbb1de50c93fa03a8229 so that the original "digest"/"signature"
        // pair continues to be generated in a buggy form, while "correct_digest"/"correct_signature" are generated
        // correctly.
        //
        // Jenkins should ignore "digest"/"signature" pair. Accepting it creates a vulnerability that allows
        // the attacker to inject a fragment at the end of the json.
        o.writeCanonical(new OutputStreamWriter(new TeeOutputStream(dos, sos), "UTF-8")).close();

        // did the digest match? this is not a part of the signature validation, but if we have a bug in the c14n
        // (which is more likely than someone tampering with update center), we can tell
        final String computedDigest = new String(Base64.encode(sha1.digest()));
        final String providedDigest = signature.optString("correct_digest");
        if (providedDigest == null) {
            return FormValidation.error("No correct_digest parameter in update center '" + getId()
                    + "'. This metadata appears to be old.");
        }
        if (!computedDigest.equalsIgnoreCase(providedDigest)) {
            return FormValidation.error("Digest mismatch: " + computedDigest + " vs " + providedDigest
                    + " in update center '" + getId() + "'");
        }

        final String providedSignature = signature.getString("correct_signature");
        if (!sig.verify(Base64.decode(providedSignature.toCharArray()))) {
            return FormValidation.error(
                    "Signature in the update center doesn't match with the certificate in update center '"
                            + getId() + "'");
        }

        if (warning != null) {
            return warning;
        }
        return FormValidation.ok();
    } catch (final GeneralSecurityException e) {
        return FormValidation.error(e, "Signature verification failed in the update center '" + getId() + "'");
    }
}

From source file:be.fedict.eid.dss.protocol.simple.SimpleDSSProtocolService.java

public BrowserPOSTResponse handleResponse(SignatureStatus signatureStatus, byte[] signedDocument,
        String artifact, X509Certificate signerCertificate, HttpSession httpSession, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    LOG.debug("handleResponse");
    String target = retrieveTarget(httpSession);
    BrowserPOSTResponse browserPOSTResponse = new BrowserPOSTResponse(target);
    browserPOSTResponse.addAttribute("SignatureStatus", signatureStatus.getStatus());

    /*// ww w  .ja  v a 2s.c o m
     * Add RelayState if available
     */
    String relayState = retrieveRelayState(httpSession);
    if (null != relayState) {
        browserPOSTResponse.addAttribute("RelayState", relayState);
    }

    if (SignatureStatus.OK == signatureStatus) {

        String signatureRequest = retrieveSignatureRequest(httpSession);
        String signatureRequestId = retrieveSignatureRequestId(httpSession);
        String encodedSignedDocument = Base64.encodeBase64String(signedDocument);

        if (null != signatureRequest) {

            browserPOSTResponse.addAttribute("SignatureResponse", encodedSignedDocument);
        } else {

            browserPOSTResponse.addAttribute("SignatureResponseId", artifact);

        }

        byte[] derSignerCertificate = signerCertificate.getEncoded();
        String encodedSignatureCertificate = Base64.encodeBase64String(derSignerCertificate);
        browserPOSTResponse.addAttribute("SignatureCertificate", encodedSignatureCertificate);

        KeyStore.PrivateKeyEntry identityPrivateKeyEntry = this.dssContext.getIdentity();
        if (null != identityPrivateKeyEntry) {
            LOG.debug("signing the response");

            if (null != signatureRequest) {
                browserPOSTResponse.addAttribute("ServiceSigned", URLEncoder.encode(
                        "target,SignatureRequest," + "SignatureResponse," + "SignatureCertificate", "UTF-8"));
            } else {
                browserPOSTResponse.addAttribute("ServiceSigned",
                        URLEncoder.encode(
                                "target,SignatureRequestId," + "SignatureResponseId," + "SignatureCertificate",
                                "UTF-8"));
            }

            // service signature
            Signature serviceSignature = Signature.getInstance("SHA1withRSA");
            serviceSignature.initSign(identityPrivateKeyEntry.getPrivateKey());
            serviceSignature.update(target.getBytes());

            if (null != signatureRequest) {
                serviceSignature.update(signatureRequest.getBytes());
                serviceSignature.update(encodedSignedDocument.getBytes());
            } else {
                serviceSignature.update(signatureRequestId.getBytes());
                serviceSignature.update(artifact.getBytes());
            }

            serviceSignature.update(encodedSignatureCertificate.getBytes());

            byte[] serviceSignatureValue = serviceSignature.sign();

            String encodedServiceSignature = Base64.encodeBase64String(serviceSignatureValue);
            browserPOSTResponse.addAttribute("ServiceSignature", encodedServiceSignature);

            // service certificate chain
            Certificate[] serviceCertificateChain = identityPrivateKeyEntry.getCertificateChain();
            browserPOSTResponse.addAttribute("ServiceCertificateChainSize",
                    Integer.toString(serviceCertificateChain.length));
            for (int certIdx = 0; certIdx < serviceCertificateChain.length; certIdx++) {
                Certificate certificate = serviceCertificateChain[certIdx];
                String encodedServiceCertificate = Base64.encodeBase64String(certificate.getEncoded());
                browserPOSTResponse.addAttribute("ServiceCertificate." + (certIdx + 1),
                        encodedServiceCertificate);
            }
        }
    }
    return browserPOSTResponse;
}

From source file:test.integ.be.fedict.commons.eid.client.JCATest.java

@Test
public void testNonRepudiationSignaturePPDU() throws Exception {

    CCID.riskPPDU(true);//from  w  w w.jav  a  2  s. c o  m

    Security.addProvider(new BeIDProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);
    PrivateKey signPrivateKey = (PrivateKey) keyStore.getKey("Signature", null);
    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initSign(signPrivateKey);
    byte[] toBeSigned = "hello world".getBytes();
    signature.update(toBeSigned);
    byte[] signatureValue = signature.sign();
    assertNotNull(signatureValue);

    Certificate[] signCertificateChain = keyStore.getCertificateChain("Signature");
    assertNotNull(signCertificateChain);
}

From source file:com.kuzumeji.platform.standard.SecurityService.java

/**
 * ?/*w  w w  .j  a  v  a 2 s.co  m*/
 * <dl>
 * <dt>?
 * <dd>SHA-512?RSA????????
 * </dl>
 * @param key ?
 * @param signature ??
 * @param plain 
 * @return ?
 */
public boolean verify(final PublicKey key, final byte[] signature, final byte[] plain) {
    try {
        final Signature verifier = Signature.getInstance(SIGN_ALGO_NAME);
        verifier.initVerify(key);
        verifier.update(plain);
        return verifier.verify(signature);
    } catch (final NoSuchAlgorithmException | InvalidKeyException | SignatureException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.structr.util.StructrLicenseManager.java

private boolean isValid(final Map<String, String> properties) {

    if (!licensePresent) {
        return false;
    }//from  w  ww .  j  av a 2s . c o  m

    final String src = collectLicenseFieldsForSignature(properties);
    final String name = properties.get(NameKey);
    final String key = properties.get(SignatureKey);
    final String hostId = properties.get(MachineKey);
    final String thisHostId = createHash();
    final String edition = properties.get(EditionKey);
    final String modules = properties.get(ModulesKey);
    final String dateString = properties.get(DateKey);
    final String startDateString = properties.get(StartKey);
    final String endDateString = properties.get(EndKey);
    final String serversString = properties.get(ServersKey);
    final Date now = new Date();

    if (StringUtils.isEmpty(key)) {

        logger.error("Unable to read key from license file.");
        return false;
    }

    try {

        final byte[] data = src.getBytes(CharSet);
        final Signature signer = Signature.getInstance(SignatureAlgorithm);
        final byte[] signature = Hex.decodeHex(key.toCharArray());

        signer.initVerify(certificate);
        signer.update(data);

        if (!signer.verify(signature)) {

            logger.error("License signature verification failed, license is not valid.");
            return false;
        }

    } catch (Throwable t) {

        logger.error("Unable to verify license.", t);
        return false;
    }

    if (StringUtils.isEmpty(name)) {

        logger.error("License file doesn't contain licensee name.");
        return false;
    }

    if (StringUtils.isEmpty(edition)) {

        logger.error("License file doesn't contain edition.");
        return false;
    }

    if (StringUtils.isEmpty(modules)) {

        logger.error("License file doesn't contain modules.");
        return false;
    }

    if (StringUtils.isEmpty(hostId)) {

        logger.error("License file doesn't contain host ID.");
        return false;
    }

    if (StringUtils.isEmpty(dateString)) {

        logger.error("License file doesn't contain license date.");
        return false;
    }

    if (StringUtils.isEmpty(startDateString)) {

        logger.error("License file doesn't contain start date.");
        return false;
    }

    if (StringUtils.isEmpty(endDateString)) {

        logger.error("License file doesn't contain end date.");
        return false;
    }

    // verify host ID
    if (!thisHostId.equals(hostId) && !"*".equals(hostId)) {

        logger.error("Host ID found in license ({}) file does not match current host ID.", hostId);
        return false;
    }

    if ("*".equals(hostId)) {

        // check volume license against server addresses
        if (StringUtils.isNotBlank(serversString)) {

            // send HostID to server
            properties.put(HostIdKey, thisHostId);

            return checkVolumeLicense(properties, serversString);
        }

        final Calendar issuedAtPlusOneMonth = GregorianCalendar.getInstance();
        final Calendar cal = GregorianCalendar.getInstance();

        // set issuedAt to license date plus one month
        issuedAtPlusOneMonth.setTime(parseDate(dateString));
        issuedAtPlusOneMonth.add(Calendar.MONTH, 1);

        // check that the license file was issued not more than one month ago
        if (cal.after(issuedAtPlusOneMonth)) {

            logger.error(
                    "Development license found in license file is not valid any more, license period ended {}.",
                    format.format(issuedAtPlusOneMonth.getTime()));
            return false;
        }
    }

    // verify that the license is valid for the current date
    final Date startDate = parseDate(startDateString);
    if (startDate != null && now.before(startDate) && !now.equals(startDate)) {

        logger.error("License found in license file is not yet valid, license period starts {}.",
                format.format(startDate.getTime()));
        return false;
    }

    // verify that the license is valid for the current date
    final Date endDate = parseDate(endDateString);
    if (endDate != null && now.after(endDate) && !now.equals(endDate)) {

        logger.error("License found in license file is not valid any more, license period ended {}.",
                format.format(endDate.getTime()));
        return false;
    }

    return true;
}