Example usage for java.security Signature initVerify

List of usage examples for java.security Signature initVerify

Introduction

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

Prototype

public final void initVerify(Certificate certificate) throws InvalidKeyException 

Source Link

Document

Initializes this object for verification, using the public key from the given certificate.

Usage

From source file:be.fedict.eid.applet.service.impl.handler.AuthenticationDataMessageHandler.java

private void verifySignature(String signatureAlgo, byte[] signatureData, PublicKey publicKey,
        HttpServletRequest request, byte[]... data) throws ServletException {
    Signature signature;
    try {/*from w ww  . ja v a  2 s  . c o m*/
        signature = Signature.getInstance(signatureAlgo);
    } catch (NoSuchAlgorithmException e) {
        throw new ServletException("algo error: " + e.getMessage(), e);
    }
    try {
        signature.initVerify(publicKey);
    } catch (InvalidKeyException e) {
        throw new ServletException("key error: " + e.getMessage(), e);
    }
    try {
        for (byte[] dataItem : data) {
            signature.update(dataItem);
        }
        boolean result = signature.verify(signatureData);
        if (false == result) {
            AuditService auditService = this.auditServiceLocator.locateService();
            if (null != auditService) {
                String remoteAddress = request.getRemoteAddr();
                auditService.identityIntegrityError(remoteAddress);
            }
            throw new ServletException("signature incorrect");
        }
    } catch (SignatureException e) {
        throw new ServletException("signature error: " + e.getMessage(), e);
    }
}

From source file:in.neoandroid.neoupdate.neoUpdate.java

private boolean checkSignature(String jsonContent, String sign) {
    Log.d(TAG, "JSON: " + jsonContent);

    if (sign == null)
        return false;
    final String publicKeyStr = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAq+6EG/fAE+zIdh5Wzqnf"
            + "Fo4nCf7t7eJcKyvk1lqX1MdkIi/fUs8HQ4aQ4jWLCO4M1Gkz1FQiXOnheGLV5MXY"
            + "c9GyaglsofvpA/pU5d16FybX2pCevbTzcm39eU+XlwQWOr8gh23tYD8G6uMX6sIJ"
            + "W+1k1FWdud9errMVm0YUScI+J4AV5xzN0IQ29h9IeNp6oFqZ2ByWog6OBMTUDFIW"
            + "q8oRvH0OuPv3zFR5rKwsbTYb5Da8lhUht04dLBA860Y4zeUu98huvS9jQPu2N4ns"
            + "Hf425FfDJ/wae+7eLdQo7uFb+Wvc+PO9U39e6vXQfa8ZkUoXHD0XZN4jsFcKYuJw" + "OwIDAQAB";
    try {/*w ww . j  a va2s  .c om*/
        byte keyBytes[] = Base64.decode(publicKeyStr.getBytes(), Base64.NO_WRAP);

        X509EncodedKeySpec publicSpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PublicKey publicKey = kf.generatePublic(publicSpec);

        Signature signer = Signature.getInstance("SHA1withRSA");
        signer.initVerify(publicKey);
        signer.update(jsonContent.getBytes(), 0, jsonContent.length());

        return signer.verify(Base64.decode(sign, Base64.NO_WRAP));
    } catch (Exception e) {
    }
    return false;
}

From source file:hudson.cli.CLI.java

/**
 * @deprecated Specific to {@link Mode#REMOTING}.
 *///w w w.  java  2s  .c o 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.");
    }//from w ww.  j a  va  2s . c o  m
    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 a  v  a 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.yourkey.billing.util.InAppBilling.java

private boolean verifySignature(String signedData, String signature) {
    try {//from   w  w w  . j  a  v  a  2 s  .  c o 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
 */// w w  w  .  j  a v  a 2 s .co m
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 {// www  . j  a  va2  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: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 w w w.j  a va2  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.ejbca.core.protocol.cmp.EndEntityCertAuthModuleTest.java

/**
 * 1- Sends a CRMF request signed by RA2Admin to RA1. Expected: Fail
 * 2- Sends a CRMF request signed by RA1Admin to RA2. Expected: Fail
 * //from  w w w  .  j  av  a 2 s .  c o m
 * @throws Exception
 */
@Test
public void test01RA1FailedCRMF() throws Exception {

    // Send CRMF message signed by RA2Admin to RA1
    String testUsername = "ra1testuser";
    X500Name testUserDN = new X500Name("CN=" + testUsername);
    KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
    AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
    PKIMessage msg = genCertReq(ca1.getSubjectDN(), testUserDN, keys, ca1.getCACertificate(), nonce, transid,
            false, null, null, null, null, pAlg, new DEROctetString(nonce));
    assertNotNull("Generating CrmfRequest failed.", msg);

    CMPCertificate[] extraCert = getCMPCert(ra2admincert);
    msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, ra2adminkeys.getPrivate(),
            pAlg.getAlgorithm().getId(), "BC");
    assertNotNull("Signing CMP message failed.", msg);
    //******************************************''''''
    Signature sig = Signature.getInstance(msg.getHeader().getProtectionAlg().getAlgorithm().getId(), "BC");
    sig.initVerify(ra2admincert.getPublicKey());
    sig.update(CmpMessageHelper.getProtectedBytes(msg));
    boolean verified = sig.verify(msg.getProtection().getBytes());
    assertTrue("Signing the message failed.", verified);
    //***************************************************

    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(msg);
    byte[] ba = bao.toByteArray();
    // Send request and receive response
    byte[] resp = sendCmpHttp(ba, 200, RA1_ALIAS);
    checkCmpResponseGeneral(resp, ca1.getSubjectDN(), testUserDN, ca1.getCACertificate(),
            msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(), false,
            null, null);
    ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
    PKIMessage respObject = null;
    try {
        respObject = PKIMessage.getInstance(asn1InputStream.readObject());
    } finally {
        asn1InputStream.close();
    }
    assertNotNull("Reading CMP response failed.", respObject);
    PKIBody body = respObject.getBody();
    assertEquals(PKIBody.TYPE_ERROR, body.getType());
    ErrorMsgContent err = (ErrorMsgContent) body.getContent();
    String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
    String expectedErrMsg = "'CN=" + RA2_ADMIN + "' is not an authorized administrator.";
    assertEquals(expectedErrMsg, errMsg);

    // Send CRMF message signed by RA1Admin to RA2
    testUsername = "ra2testuser";
    testUserDN = new X500Name("CN=" + testUsername);
    keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
    pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
    msg = genCertReq(ca2.getSubjectDN(), testUserDN, keys, ca2.getCACertificate(), nonce, transid, false, null,
            null, null, null, pAlg, new DEROctetString(nonce));
    assertNotNull("Generating CrmfRequest failed.", msg);

    extraCert = getCMPCert(ra1admincert);
    msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, ra1adminkeys.getPrivate(),
            pAlg.getAlgorithm().getId(), "BC");
    assertNotNull("Signing CMP message failed.", msg);
    //******************************************''''''
    sig = Signature.getInstance(msg.getHeader().getProtectionAlg().getAlgorithm().getId(), "BC");
    sig.initVerify(ra1admincert.getPublicKey());
    sig.update(CmpMessageHelper.getProtectedBytes(msg));
    verified = sig.verify(msg.getProtection().getBytes());
    assertTrue("Signing the message failed.", verified);
    //***************************************************

    bao = new ByteArrayOutputStream();
    out = new DEROutputStream(bao);
    out.writeObject(msg);
    ba = bao.toByteArray();
    // Send request and receive response
    resp = sendCmpHttp(ba, 200, RA2_ALIAS);
    checkCmpResponseGeneral(resp, ca2.getSubjectDN(), testUserDN, ca2.getCACertificate(),
            msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(), false,
            null, null);
    asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
    try {
        respObject = PKIMessage.getInstance(asn1InputStream.readObject());
    } finally {
        asn1InputStream.close();
    }
    assertNotNull("Reading CMP response failed.", respObject);
    body = respObject.getBody();
    assertEquals(PKIBody.TYPE_ERROR, body.getType());
    err = (ErrorMsgContent) body.getContent();
    errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
    expectedErrMsg = "'CN=" + RA1_ADMIN + "' is not an authorized administrator.";
    assertEquals(expectedErrMsg, errMsg);

}