Example usage for java.security Signature update

List of usage examples for java.security Signature update

Introduction

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

Prototype

public final void update(ByteBuffer data) throws SignatureException 

Source Link

Document

Updates the data to be signed or verified using the specified ByteBuffer.

Usage

From source file:hudson.cli.CLI.java

/**
 * @deprecated Specific to {@link Mode#REMOTING}.
 *///  w  w  w. java2 s  .  co m
@Deprecated
private Channel connectViaCliPort(URL jenkins, CliPort clip) throws IOException {
    LOGGER.log(FINE, "Trying to connect directly via Remoting over TCP/IP to {0}", clip.endpoint);

    if (authorization != null) {
        LOGGER.warning("-auth ignored when using JNLP agent port");
    }

    final Socket s = new Socket();
    // this prevents a connection from silently terminated by the router in between or the other peer
    // and that goes without unnoticed. However, the time out is often very long (for example 2 hours
    // by default in Linux) that this alone is enough to prevent that.
    s.setKeepAlive(true);
    // we take care of buffering on our own
    s.setTcpNoDelay(true);
    OutputStream out;

    if (httpsProxyTunnel != null) {
        String[] tokens = httpsProxyTunnel.split(":");
        LOGGER.log(Level.FINE, "Using HTTP proxy {0}:{1} to connect to CLI port",
                new Object[] { tokens[0], tokens[1] });
        s.connect(new InetSocketAddress(tokens[0], Integer.parseInt(tokens[1])));
        PrintStream o = new PrintStream(s.getOutputStream());
        o.print("CONNECT " + clip.endpoint.getHostString() + ":" + clip.endpoint.getPort()
                + " HTTP/1.0\r\n\r\n");

        // read the response from the proxy
        ByteArrayOutputStream rsp = new ByteArrayOutputStream();
        while (!rsp.toString("ISO-8859-1").endsWith("\r\n\r\n")) {
            int ch = s.getInputStream().read();
            if (ch < 0)
                throw new IOException("Failed to read the HTTP proxy response: " + rsp);
            rsp.write(ch);
        }
        String head = new BufferedReader(new StringReader(rsp.toString("ISO-8859-1"))).readLine();

        if (head == null) {
            throw new IOException("Unexpected empty response");
        }
        if (!(head.startsWith("HTTP/1.0 200 ") || head.startsWith("HTTP/1.1 200 "))) {
            s.close();
            LOGGER.log(Level.SEVERE,
                    "Failed to tunnel the CLI port through the HTTP proxy. Falling back to HTTP.");
            throw new IOException("Failed to establish a connection through HTTP proxy: " + rsp);
        }

        // HTTP proxies (at least the one I tried --- squid) doesn't seem to do half-close very well.
        // So instead of relying on it, we'll just send the close command and then let the server
        // cut their side, then close the socket after the join.
        out = new SocketOutputStream(s) {
            @Override
            public void close() throws IOException {
                // ignore
            }
        };
    } else {
        s.connect(clip.endpoint, 3000);
        out = SocketChannelStream.out(s);
    }

    closables.add(new Closeable() {
        public void close() throws IOException {
            s.close();
        }
    });

    Connection c = new Connection(SocketChannelStream.in(s), out);

    switch (clip.version) {
    case 1:
        DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        dos.writeUTF("Protocol:CLI-connect");
        // we aren't checking greeting from the server here because I'm too lazy. It gets ignored by Channel constructor.
        break;
    case 2:
        DataInputStream dis = new DataInputStream(s.getInputStream());
        dos = new DataOutputStream(s.getOutputStream());
        dos.writeUTF("Protocol:CLI2-connect");
        String greeting = dis.readUTF();
        if (!greeting.equals("Welcome"))
            throw new IOException("Handshaking failed: " + greeting);
        try {
            byte[] secret = c.diffieHellman(false).generateSecret();
            SecretKey sessionKey = new SecretKeySpec(Connection.fold(secret, 128 / 8), "AES");
            c = c.encryptConnection(sessionKey, "AES/CFB8/NoPadding");

            // validate the instance identity, so that we can be sure that we are talking to the same server
            // and there's no one in the middle.
            byte[] signature = c.readByteArray();

            if (clip.identity != null) {
                Signature verifier = Signature.getInstance("SHA1withRSA");
                verifier.initVerify(clip.getIdentity());
                verifier.update(secret);
                if (!verifier.verify(signature))
                    throw new IOException("Server identity signature validation failed.");
            }

        } catch (GeneralSecurityException e) {
            throw (IOException) new IOException("Failed to negotiate transport security").initCause(e);
        }
    }

    return new Channel("CLI connection to " + jenkins, pool, new BufferedInputStream(c.in),
            new BufferedOutputStream(c.out));
}

From source file:com.google.appengine.tck.appidentity.AppIdentityServiceTest.java

private boolean verifySignatureWithAllCertsForApp(byte[] blob, byte[] signedBlob,
        Collection<PublicCertificate> certsForApp) {

    if (certsForApp.isEmpty()) {
        throw new IllegalStateException("No certificates to validate.  Must have at least 1.");
    }/* w w w . j a  v  a 2s  .  com*/
    int currentCertNum = 0;
    int totalValid = 0;
    int totalInvalid = 0;
    List<Exception> allExceptions = new ArrayList<>();

    for (PublicCertificate publicCert : certsForApp) {
        Signature signature;
        Certificate cert = null;
        currentCertNum++;

        log.info("Processing certNum:" + currentCertNum);
        try {
            byte[] certBytes = publicCert.getX509CertificateInPemFormat().getBytes("UTF-8");
            InputStream stream = new ByteArrayInputStream(certBytes);
            signature = Signature.getInstance("SHA256withRSA"); // Make this configurable?
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            cert = cf.generateCertificate(stream);
            log.info(cert.toString());

            PublicKey pk = cert.getPublicKey();
            signature.initVerify(pk);
            signature.update(blob);
            boolean isValidSignature = signature.verify(signedBlob);

            if (isValidSignature) {
                totalValid++;
            } else {
                totalInvalid++;
            }
            log.info("certNum:" + currentCertNum + ": is valid:" + isValidSignature);

            // These can be thrown:
            // UnsupportedEncodingException, NoSuchAlgorithmException, CertificateException,
            // SignatureException, InvalidKeyException
        } catch (Exception e) {
            Exception logException = createExceptionForLog(e, currentCertNum, cert);
            allExceptions.add(logException);
            log.info(e.toString());
        }
    }
    String summary = "totalCerts:" + certsForApp.size() + ": totalValid:" + totalValid + " totalInvalid:"
            + totalInvalid + " totalExceptions:" + allExceptions.size();
    log.info(summary);

    // At least one certificate caused an exception so make test Error.
    if (allExceptions.size() > 0) {
        throw new IllegalStateException(summary + "\n\n" + exceptionListToString(allExceptions));
    }

    // At least one signature was valid and no exceptions thrown.
    return (totalValid > 0);
}

From source file:org.ejbca.core.protocol.cmp.authentication.EndEntityCertificateAuthenticationModule.java

@Override
/*//from  ww w  .  j  ava 2s .  c om
 * Verifies the signature of 'msg'. msg should be signed and the signer's certificate should be  
 * attached in msg in the extraCert field.  
 * 
 * When successful, the authentication string is set.
 */
public boolean verifyOrExtract(final PKIMessage msg, final String username) {

    //Check that msg is signed
    if (msg.getProtection() == null) {
        this.errorMessage = "PKI Message is not athenticated properly. No PKI protection is found.";
        return false;
    }

    // Read the extraCert and store it in a local variable
    extraCert = getExtraCert(msg);
    if (extraCert == null) {
        this.errorMessage = "Error while reading the certificate in the extraCert field";
        return false;
    }

    boolean vendormode = impl.isVendorCertificateMode(msg.getBody().getType(), this.confAlias);
    boolean omitVerifications = cmpConfiguration.getOmitVerificationsInEEC(confAlias);
    boolean ramode = cmpConfiguration.getRAMode(confAlias);
    if (log.isDebugEnabled()) {
        log.debug("CMP is operating in RA mode: " + this.cmpConfiguration.getRAMode(this.confAlias));
        log.debug("CMP is operating in Vendor mode: " + vendormode);
        log.debug("CMP message already been authenticated: " + authenticated);
        log.debug("Omitting som verifications: " + omitVerifications);
    }

    //----------------------------------------------------------------------------------------
    // Perform the different checks depending on the configuration and previous authentication
    //----------------------------------------------------------------------------------------

    // Not allowed combinations.
    if (ramode && vendormode) {
        this.errorMessage = "Vendor mode and RA mode cannot be combined";
        return false;
    }
    if (omitVerifications && (!ramode || !authenticated)) {
        this.errorMessage = "Omitting some verifications can only be accepted in RA mode and when the "
                + "CMP request has already been authenticated, for example, through the use of NestedMessageContent";
        return false;
    }

    // Accepted combinations
    if (omitVerifications && ramode && authenticated) {
        // Do nothing here
        if (log.isDebugEnabled()) {
            log.debug(
                    "Skipping some verification of the extraCert certificate in RA mode and an already authenticated CMP message, tex. through NestedMessageContent");
        }
    } else if (ramode) {

        // Get the CA to use for the authentication
        CAInfo cainfo = getCAInfoByName(authenticationparameter);
        if (cainfo == null)
            return false;

        // Check that extraCert is in the Database
        CertificateInfo certinfo = certSession.getCertificateInfo(CertTools.getFingerprintAsString(extraCert));
        if (certinfo == null) {
            this.errorMessage = "The certificate attached to the PKIMessage in the extraCert field could not be found in the database.";
            return false;
        }

        // More extraCert verifications
        if (!isExtraCertIssuedByCA(cainfo) || !isExtraCertValid() || !isExtraCertActive(certinfo)) {
            return false;
        }

        // Check that extraCert belong to an admin with sufficient access rights
        if (!isAuthorizedAdmin(certinfo, msg, cainfo.getCAId())) {
            this.errorMessage = "'" + CertTools.getSubjectDN(extraCert)
                    + "' is not an authorized administrator.";
            return false;
        }

    } else if (!ramode) { // client mode

        String extraCertUsername = null;
        if (vendormode) {

            // Check that extraCert is issued  by a configured VendorCA
            if (!impl.isExtraCertIssuedByVendorCA(admin, this.confAlias, extraCert)) {
                this.errorMessage = "The certificate in extraCert field is not issued by any of the configured Vendor CAs: "
                        + cmpConfiguration.getVendorCA(confAlias);
                return false;
            }

            // Extract the username from extraCert to use for  further authentication
            String subjectDN = CertTools.getSubjectDN(extraCert);
            extraCertUsername = CertTools.getPartFromDN(subjectDN,
                    this.cmpConfiguration.getExtractUsernameComponent(this.confAlias));
            if (log.isDebugEnabled()) {
                log.debug("Username (" + extraCertUsername + ") was extracted from the '"
                        + this.cmpConfiguration.getExtractUsernameComponent(this.confAlias)
                        + "' part of the subjectDN of the certificate in the 'extraCerts' field.");
            }

        } else {

            // Get the CA to use for the authentication
            CAInfo cainfo = getCAInfoByIssuer(CertTools.getIssuerDN(extraCert));

            // Check that extraCert is in the Database
            CertificateInfo certinfo = certSession
                    .getCertificateInfo(CertTools.getFingerprintAsString(extraCert));
            if (certinfo == null) {
                this.errorMessage = "The certificate attached to the PKIMessage in the extraCert field could not be found in the database.";
                return false;
            }

            // More extraCert verifications
            if (!isExtraCertIssuedByCA(cainfo) || !isExtraCertValid() || !isExtraCertActive(certinfo)) {
                return false;
            }

            // Extract the username from extraCert to use for  further authentication
            extraCertUsername = certinfo.getUsername();
        }

        // Check if this certificate belongs to the user
        if ((username != null) && (extraCertUsername != null)) {
            if (!StringUtils.equals(username, extraCertUsername)) {
                this.errorMessage = "The End Entity certificate attached to the PKIMessage in the extraCert field does not belong to user '"
                        + username + "'";
                if (log.isDebugEnabled()) {
                    // Use a different debug message, as not to reveal too much information
                    log.debug(this.errorMessage + ", but to user '" + extraCertUsername + "'");
                }
                return false;
            }

            //set the password of the request to this user's password so it can later be used when issuing the certificate
            if (log.isDebugEnabled()) {
                log.debug(
                        "The End Entity certificate attached to the PKIMessage in the extraCert field belongs to user '"
                                + username + "'.");
                log.debug("Extracting and setting password for user '" + username + "'.");
            }
            try {
                EndEntityInformation user = eeAccessSession.findUser(admin, username);
                password = user.getPassword();
                if (password == null) {
                    password = genRandomPwd();
                    user.setPassword(password);
                    eeManagementSession.changeUser(admin, user, false);
                }
            } catch (AuthorizationDeniedException e) {
                if (log.isDebugEnabled()) {
                    log.debug(e.getLocalizedMessage());
                }
                this.errorMessage = e.getLocalizedMessage();
                return false;
            } catch (CADoesntExistsException e) {
                if (log.isDebugEnabled()) {
                    log.debug(e.getLocalizedMessage());
                }
                this.errorMessage = e.getLocalizedMessage();
                return false;
            } catch (UserDoesntFullfillEndEntityProfile e) {
                if (log.isDebugEnabled()) {
                    log.debug(e.getLocalizedMessage());
                }
                this.errorMessage = e.getLocalizedMessage();
                return false;
            } catch (WaitingForApprovalException e) {
                if (log.isDebugEnabled()) {
                    log.debug(e.getLocalizedMessage());
                }
                this.errorMessage = e.getLocalizedMessage();
                return false;
            } catch (EjbcaException e) {
                if (log.isDebugEnabled()) {
                    log.debug(e.getLocalizedMessage());
                }
                this.errorMessage = e.getLocalizedMessage();
                return false;
            }
        }
    }

    //-------------------------------------------------------------
    //Begin the signature verification process.
    //Verify the signature of msg using the public key of extraCert
    //-------------------------------------------------------------
    try {
        final Signature sig = Signature.getInstance(msg.getHeader().getProtectionAlg().getAlgorithm().getId(),
                "BC");
        sig.initVerify(extraCert.getPublicKey());
        sig.update(CmpMessageHelper.getProtectedBytes(msg));
        if (sig.verify(msg.getProtection().getBytes())) {
            if (password == null) {
                // If not set earlier
                password = genRandomPwd();
            }
        } else {
            this.errorMessage = "Failed to verify the signature in the PKIMessage";
            return false;
        }
    } catch (InvalidKeyException e) {
        if (log.isDebugEnabled()) {
            log.debug(e.getLocalizedMessage());
        }
        this.errorMessage = e.getLocalizedMessage();
        return false;
    } catch (NoSuchAlgorithmException e) {
        if (log.isDebugEnabled()) {
            log.debug(e.getLocalizedMessage());
        }
        this.errorMessage = e.getLocalizedMessage();
        return false;
    } catch (NoSuchProviderException e) {
        if (log.isDebugEnabled()) {
            log.debug(e.getLocalizedMessage());
        }
        this.errorMessage = e.getLocalizedMessage();
        return false;
    } catch (SignatureException e) {
        if (log.isDebugEnabled()) {
            log.debug(e.getLocalizedMessage());
        }
        this.errorMessage = e.getLocalizedMessage();
        return false;
    }

    return this.password != null;
}

From source file:com.vmware.identity.samlservice.impl.SamlServiceImpl.java

@Override
public String signMessage(String message) throws IllegalStateException {
    Validate.notNull(this.getSignAlgorithm());
    Validate.notNull(this.getPrivateKey());

    try {/*from   www  .jav  a2  s. co m*/
        Signature sig = Signature.getInstance(this.getSignAlgorithm().getAlgorithmName());
        sig.initSign(privateKey);

        byte[] messageBytes = message.getBytes("UTF-8");
        sig.update(messageBytes);

        byte[] sigBytes = sig.sign();
        String signature = Shared.encodeBytes(sigBytes);
        if (signature == null || signature.isEmpty()) {
            log.debug("Invalid signature - either null or empty. ");
        }

        return signature;
    } catch (Exception e) {
        log.error("Caught exception while signing  message " + message + ", sigAlg "
                + this.getSignAlgorithm().getAlgorithmName());
        throw new IllegalStateException(e);
    }
}

From source file:com.yourkey.billing.util.InAppBilling.java

private boolean verifySignature(String signedData, String signature) {
    try {//w w  w.j a  v  a  2  s .  co  m
        // do it only once
        if (appPublicKey == null) {
            // decode application public key from base64 to binary   
            byte[] decodedKey = decodeBase64(appPublicKeyStr);
            if (decodedKey == null)
                return (false);

            // convert public key from binary to PublicKey object
            appPublicKey = KeyFactory.getInstance(KEY_FACTORY_ALGORITHM)
                    .generatePublic(new X509EncodedKeySpec(decodedKey));
        }

        // decode signature
        byte[] decodedSig = decodeBase64(signature);
        if (decodedSig == null)
            return (false);

        // verify signature
        Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM);
        sig.initVerify(appPublicKey);
        sig.update(signedData.getBytes());
        return (sig.verify(decodedSig));
    } catch (Exception e) {
        return (false);
    }
}

From source file:org.ejbca.core.protocol.scep.ProtocolScepHttpTest.java

/**
 * checks that a public and private key matches by signing and verifying a message
 *///from   ww w . j a v a  2  s .com
private boolean checkKeys(PrivateKey priv, PublicKey pub)
        throws SignatureException, NoSuchAlgorithmException, InvalidKeyException {
    Signature signer = Signature.getInstance("SHA1WithRSA");
    signer.initSign(priv);
    signer.update("PrimeKey".getBytes());
    byte[] signature = signer.sign();

    Signature signer2 = Signature.getInstance("SHA1WithRSA");
    signer2.initVerify(pub);
    signer2.update("PrimeKey".getBytes());
    return signer2.verify(signature);
}

From source file:edu.ucsb.eucalyptus.transport.query.WalrusQuerySecurityHandler.java

public UserInfo handle(String addr, String verb, Map<String, String> parameters, Map<String, String> headers)
        throws QuerySecurityException {
    CaseInsensitiveMap hdrs = new CaseInsensitiveMap(headers);

    //this.checkParameters( hdrs );
    //:: check the signature :://

    if (hdrs.containsKey(StorageQuerySecurityHandler.StorageSecurityParameters.EucaSignature)) {
        //possible internal request -- perform authentication using internal credentials
        String date = (String) hdrs.remove(SecurityParameter.Date);
        String eucaCert = (String) hdrs.remove(StorageQuerySecurityHandler.StorageSecurityParameters.EucaCert);
        String signature = (String) hdrs
                .remove(StorageQuerySecurityHandler.StorageSecurityParameters.EucaSignature);
        String data = verb + "\n" + date + "\n" + addr + "\n";

        Signature sig;
        boolean valid = false;
        try {/*from  w w  w.  java  2  s  .  co m*/
            byte[] bytes = Base64.decode(eucaCert);
            String certString = new String(bytes);
            PEMReader pemReader = new PEMReader(new StringReader(certString));
            X509Certificate cert = (X509Certificate) pemReader.readObject();
            AbstractKeyStore keyStore = ServiceKeyStore.getInstance();
            if (keyStore.getCertificateAlias(cert) != null) {
                //cert found in keystore
                PublicKey publicKey = cert.getPublicKey();
                sig = Signature.getInstance("SHA1withRSA");

                sig.initVerify(publicKey);
                sig.update(data.getBytes());
                valid = sig.verify(Base64.decode(signature));
            } else {
                LOG.warn("WalrusQuerySecurityHandler(): certificate not found in keystore");
            }
        } catch (Exception ex) {
            LOG.warn("Authentication exception: " + ex.getMessage());
            ex.printStackTrace();
        }

        if (!valid) {
            throw new QuerySecurityException("User authentication failed.");
        }
        //run as admin
        UserInfo admin = new UserInfo(EucalyptusProperties.NAME);
        admin.setIsAdministrator(Boolean.TRUE);
        return admin;
    } else if (hdrs.containsKey(WalrusProperties.FormField.FormUploadPolicyData)) {
        String data = (String) hdrs.remove(WalrusProperties.FormField.FormUploadPolicyData);
        String auth_part = (String) hdrs.remove(SecurityParameter.Authorization);

        if (auth_part != null) {
            String sigString[] = getSigInfo(auth_part);
            String signature = sigString[1];
            return getUserInfo(sigString[0], signature, data, false);
        }
        throw new QuerySecurityException("User authentication failed.");
    } else {
        //external user request
        String date;
        String verifyDate;
        if (hdrs.containsKey("x-amz-date")) {
            date = "";
            verifyDate = (String) hdrs.get("x-amz-date");
        } else {
            date = (String) hdrs.remove(SecurityParameter.Date);
            verifyDate = date;
            if (date == null || date.length() <= 0)
                throw new QuerySecurityException("User authentication failed. Date must be specified.");
        }

        try {
            Date dateToVerify = DateUtil.parseDate(verifyDate);
            Date currentDate = new Date();
            if (Math.abs(currentDate.getTime() - dateToVerify.getTime()) > EXPIRATION_LIMIT)
                throw new QuerySecurityException("Message expired. Sorry.");
        } catch (Exception ex) {
            throw new QuerySecurityException("Unable to parse date.");
        }
        String content_md5 = (String) hdrs.remove("Content-MD5");
        content_md5 = content_md5 == null ? "" : content_md5;
        String content_type = (String) hdrs.remove("Content-Type");
        content_type = content_type == null ? "" : content_type;

        String[] addrStrings = addr.split("\\?");
        String addrString = addrStrings[0];

        if (addrStrings.length > 1) {
            for (SubResource subResource : SubResource.values()) {
                if (addr.endsWith(subResource.toString())) {
                    addrString += "?" + subResource.toString();
                    break;
                }
            }
        }

        String data = verb + "\n" + content_md5 + "\n" + content_type + "\n" + date + "\n"
                + getCanonicalizedAmzHeaders(hdrs) + addrString;

        String auth_part = hdrs.remove(SecurityParameter.Authorization);

        if (auth_part != null) {
            String sigString[] = getSigInfo(auth_part);
            String signature = sigString[1];
            return getUserInfo(sigString[0], signature, data, false);
        } else if (parameters.containsKey(SecurityParameter.AWSAccessKeyId.toString())) {
            //query string authentication
            String accesskeyid = parameters.remove(SecurityParameter.AWSAccessKeyId.toString());
            try {
                String signature = URLDecoder.decode(parameters.remove(SecurityParameter.Signature.toString()),
                        "UTF-8");
                if (signature == null) {
                    throw new QuerySecurityException("User authentication failed. Null signature.");
                }
                String expires = parameters.remove(SecurityParameter.Expires.toString());
                if (expires == null) {
                    throw new QuerySecurityException("Authentication failed. Expires must be specified.");
                }
                if (checkExpires(expires)) {
                    String stringToSign = verb + "\n" + content_md5 + "\n" + content_type + "\n"
                            + Long.parseLong(expires) + "\n" + getCanonicalizedAmzHeaders(hdrs) + addrString;
                    return getUserInfo(accesskeyid, signature, stringToSign, true);
                } else {
                    throw new QuerySecurityException("Cannot process request. Expired.");
                }
            } catch (Exception ex) {
                throw new QuerySecurityException("Could not verify request " + ex.getMessage());
            }
        } else {
            //anonymous request
            return null;
        }
    }
}

From source file:zlicense.de.schlichtherle.xml.GenericCertificate.java

public final synchronized void sign(Object paramObject, PrivateKey paramPrivateKey, Signature paramSignature)
        throws NullPointerException, GenericCertificateIsLockedException, PropertyVetoException,
        PersistenceServiceException, InvalidKeyException {
    if (paramPrivateKey == null) {
        throw new NullPointerException("signingKey");
    }/*from   w ww.jav a2  s  .  co  m*/
    if (paramSignature == null) {
        throw new NullPointerException("signingEngine");
    }
    PropertyChangeEvent localPropertyChangeEvent = new PropertyChangeEvent(this, "locked",
            Boolean.valueOf(isLocked()), Boolean.TRUE);
    if (isLocked()) {
        throw new GenericCertificateIsLockedException(localPropertyChangeEvent);
    }
    fireVetoableChange(localPropertyChangeEvent);
    try {
        byte[] arrayOfByte1 = PersistenceService.store2ByteArray(paramObject);
        paramSignature.initSign(paramPrivateKey);
        paramSignature.update(arrayOfByte1);
        byte[] arrayOfByte2 = Base64.encodeBase64(paramSignature.sign());
        String str = new String(arrayOfByte2, 0, arrayOfByte2.length, "US-ASCII");
        setEncoded(new String(arrayOfByte1, "UTF-8"));
        setSignature(str);
        setSignatureAlgorithm(paramSignature.getAlgorithm());
        setSignatureEncoding("US-ASCII/Base64");
    } catch (UnsupportedEncodingException localUnsupportedEncodingException) {
        throw new AssertionError(localUnsupportedEncodingException);
    } catch (SignatureException localSignatureException) {
        throw new AssertionError(localSignatureException);
    }
    this.locked = true;
    firePropertyChange(localPropertyChangeEvent);
}

From source file:org.hyperledger.fabric.sdk.security.CryptoPrimitives.java

@Override
public boolean verify(byte[] pemCertificate, String signatureAlgorithm, byte[] signature, byte[] plainText)
        throws CryptoException {
    boolean isVerified = false;

    if (plainText == null || signature == null || pemCertificate == null) {
        return false;
    }//from  ww  w .ja  v  a  2 s  . c o m

    if (config.extraLogLevel(10)) {
        if (null != diagnosticFileDumper) {
            StringBuilder sb = new StringBuilder(10000);
            sb.append("plaintext in hex: ").append(DatatypeConverter.printHexBinary(plainText)).append("\n")
                    .append("signature in hex: " + DatatypeConverter.printHexBinary(signature)).append("\n")
                    .append("PEM cert in hex: " + DatatypeConverter.printHexBinary(pemCertificate));
            logger.trace("verify :  " + diagnosticFileDumper.createDiagnosticFile(sb.toString()));
        }
    }

    try {

        X509Certificate certificate = getX509Certificate(pemCertificate);

        if (certificate != null) {

            isVerified = validateCertificate(certificate);
            if (isVerified) { // only proceed if cert is trusted

                Signature sig = Signature.getInstance(signatureAlgorithm);
                sig.initVerify(certificate);
                sig.update(plainText);
                isVerified = sig.verify(signature);
            }
        }
    } catch (InvalidKeyException e) {
        CryptoException ex = new CryptoException("Cannot verify signature. Error is: " + e.getMessage()
                + "\r\nCertificate: " + DatatypeConverter.printHexBinary(pemCertificate), e);
        logger.error(ex.getMessage(), ex);
        throw ex;
    } catch (NoSuchAlgorithmException | SignatureException e) {
        CryptoException ex = new CryptoException(
                "Cannot verify. Signature algorithm is invalid. Error is: " + e.getMessage(), e);
        logger.error(ex.getMessage(), ex);
        throw ex;
    }

    return isVerified;
}

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

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

    if (!licensePresent) {
        return false;
    }/*ww  w .j  a  v a 2  s.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;
}