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:com.tremolosecurity.proxy.auth.SAML2Auth.java

private String procLogoutResp(HttpServletRequest request, HttpServletResponse response,
        DocumentBuilderFactory factory, String saml, String relayState, String url)
        throws ParserConfigurationException, SAXException, IOException, UnmarshallingException, Exception,
        UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException, SignatureException,
        ServletException {/*from ww w .j  a v a 2s  . c o  m*/

    LogoutResponseUnmarshaller marshaller = new LogoutResponseUnmarshaller();
    DocumentBuilder builder = factory.newDocumentBuilder();

    Element root = builder.parse(new InputSource(new StringReader(saml))).getDocumentElement();

    LogoutResponse logout = (LogoutResponse) marshaller.unmarshall(root);

    String issuer = logout.getIssuer().getValue();

    boolean found = false;

    String algType = null;
    String logoutURL = null;
    String sigKeyName = null;

    //Search for the right mechanism configuration
    for (String chainname : cfgMgr.getAuthChains().keySet()) {
        AuthChainType act = cfgMgr.getAuthChains().get(chainname);
        for (AuthMechType amt : act.getAuthMech()) {
            for (ParamType pt : amt.getParams().getParam()) {
                if (pt.getName().equalsIgnoreCase("entityID") && pt.getValue().equalsIgnoreCase(issuer)) {
                    //found the correct mechanism
                    found = true;

                    for (ParamType ptx : amt.getParams().getParam()) {
                        if (ptx.getName().equalsIgnoreCase("sigAlg")) {
                            algType = ptx.getValue();
                        } else if (ptx.getName().equalsIgnoreCase("logoutURL")) {
                            logoutURL = ptx.getValue();
                        } else if (ptx.getName().equalsIgnoreCase("idpSigKeyName")) {
                            sigKeyName = ptx.getValue();
                        }
                    }

                    break;

                }
            }

            if (found) {
                break;
            }
        }

        if (found) {
            break;
        }
    }

    if (!found) {
        throw new ServletException("Entity ID '" + issuer + "' not found");
    }

    String authnSig = request.getParameter("Signature");
    if (authnSig != null) {
        String sigAlg = request.getParameter("SigAlg");
        StringBuffer query = new StringBuffer();

        String qs = request.getQueryString();
        query.append(OpenSAMLUtils.getRawQueryStringParameter(qs, "SAMLResponse"));
        query.append('&');
        query.append(OpenSAMLUtils.getRawQueryStringParameter(qs, "RelayState"));
        query.append('&');
        query.append(OpenSAMLUtils.getRawQueryStringParameter(qs, "SigAlg"));

        java.security.cert.X509Certificate cert = this.cfgMgr.getCertificate(sigKeyName);

        String xmlAlg = SAML2Auth.xmlDigSigAlgs.get(algType);

        if (!sigAlg.equalsIgnoreCase(xmlAlg)) {
            throw new Exception("Invalid signature algorithm : '" + sigAlg + "'");
        }

        /*if (! logout.getDestination().equals(request.getRequestURL().toString())) {
           throw new Exception("Invalid destination");
        }*/

        java.security.Signature sigv = java.security.Signature
                .getInstance(SAML2Auth.javaDigSigAlgs.get(algType));

        sigv.initVerify(cert.getPublicKey());
        sigv.update(query.toString().getBytes("UTF-8"));

        if (!sigv.verify(Base64.decodeBase64(authnSig.getBytes("UTF-8")))) {
            throw new Exception("Signature verification failed");
        }

    }

    response.sendRedirect(logoutURL);

    return logoutURL;
}

From source file:com.tremolosecurity.proxy.auth.SAML2Auth.java

private String procLogoutReq(HttpServletRequest request, HttpServletResponse response,
        DocumentBuilderFactory factory, String saml, String relayState, String url)
        throws ParserConfigurationException, SAXException, IOException, UnmarshallingException, Exception,
        UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException, SignatureException,
        ServletException {/*from ww  w  . ja v  a2s .  c o  m*/

    LogoutRequestUnmarshaller marshaller = new LogoutRequestUnmarshaller();
    DocumentBuilder builder = factory.newDocumentBuilder();

    Element root = builder.parse(new InputSource(new StringReader(saml))).getDocumentElement();

    org.opensaml.saml.saml2.core.impl.LogoutRequestImpl logout = (org.opensaml.saml.saml2.core.impl.LogoutRequestImpl) marshaller
            .unmarshall(root);

    String issuer = logout.getIssuer().getValue();

    boolean found = false;

    String algType = null;
    String logoutURL = null;
    String sigKeyName = null;

    //Search for the right mechanism configuration
    for (String chainname : cfgMgr.getAuthChains().keySet()) {
        AuthChainType act = cfgMgr.getAuthChains().get(chainname);
        for (AuthMechType amt : act.getAuthMech()) {
            for (ParamType pt : amt.getParams().getParam()) {
                if (pt.getName().equalsIgnoreCase("entityID") && pt.getValue().equalsIgnoreCase(issuer)) {
                    //found the correct mechanism
                    found = true;

                    for (ParamType ptx : amt.getParams().getParam()) {
                        if (ptx.getName().equalsIgnoreCase("sigAlg")) {
                            algType = ptx.getValue();
                        } else if (ptx.getName().equalsIgnoreCase("triggerLogoutURL")) {
                            logoutURL = ptx.getValue();
                        } else if (ptx.getName().equalsIgnoreCase("idpSigKeyName")) {
                            sigKeyName = ptx.getValue();
                        }
                    }

                    break;

                }
            }

            if (found) {
                break;
            }
        }

        if (found) {
            break;
        }
    }

    if (!found) {
        throw new ServletException("Entity ID '" + issuer + "' not found");
    }

    String authnSig = request.getParameter("Signature");
    if (authnSig != null) {
        String sigAlg = request.getParameter("SigAlg");
        StringBuffer query = new StringBuffer();

        String qs = request.getQueryString();
        query.append(OpenSAMLUtils.getRawQueryStringParameter(qs, "SAMLRequest"));
        query.append('&');
        if (request.getParameter("RelayState") != null) {
            query.append(OpenSAMLUtils.getRawQueryStringParameter(qs, "RelayState"));
            query.append('&');
        }

        query.append(OpenSAMLUtils.getRawQueryStringParameter(qs, "SigAlg"));

        java.security.cert.X509Certificate cert = this.cfgMgr.getCertificate(sigKeyName);

        String xmlAlg = SAML2Auth.xmlDigSigAlgs.get(algType);

        if (!sigAlg.equalsIgnoreCase(xmlAlg)) {
            throw new Exception("Invalid signature algorithm : '" + sigAlg + "'");
        }

        /*if (! logout.getDestination().equals(request.getRequestURL().toString())) {
           throw new Exception("Invalid destination");
        }*/

        java.security.Signature sigv = java.security.Signature
                .getInstance(SAML2Auth.javaDigSigAlgs.get(algType));

        sigv.initVerify(cert.getPublicKey());
        sigv.update(query.toString().getBytes("UTF-8"));

        if (!sigv.verify(Base64.decodeBase64(authnSig.getBytes("UTF-8")))) {
            throw new Exception("Signature verification failed");
        }

    }

    response.sendRedirect(logoutURL);

    return logoutURL;
}

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

/**
 * // w  w  w . j  a va2s.c om
 * Verifies the digital signature of the encoded content in this
 * certificate and locks it.
 * <p>
 * Please note the following:
 * <ul>
 * <li>This method will throw a <tt>PropertyVetoException</tt> if this
 *     certificate is already locked, i.e. if it has been signed or
 *     verified before.</li>
 * <li>Because this method locks this certificate, a subsequent call to
 *     {@link #sign(Object, PrivateKey, Signature)} or
 *     {@link #verify(PublicKey, Signature)} is redundant
 *     and will throw a <tt>PropertyVetoException</tt>.
 *     Use {@link #isLocked()} to detect whether a
 *     generic certificate has been successfuly signed or verified before
 *     or call {@link #getContent()} and expect an 
 *     Exception to be thrown if it hasn't.</li>
 * <li>There is no way to unlock this certificate.
 *     Call the copy constructor of {@link GenericCertificate} if you
 *     need an unlocked copy of the certificate.</li>
 * </ul>
 * 
 * @param verificationKey The public key for verification
 *        - may <em>not</em> be <tt>null</tt>.
 * @param verificationEngine The signature verification engine
 *        - may <em>not</em> be <tt>null</tt>.
 * 
 * @throws NullPointerException If the preconditions for the parameters
 *         do not hold.
 * @throws GenericCertificateIsLockedException If this certificate is
 *         already locked by signing or verifying it before.
 *         Note that this is actually a subclass of
 *         {@link PropertyVetoException}.
 * @throws PropertyVetoException If locking the certifificate (and thus
 *         verifying the object) is vetoed by any listener.
 * @throws InvalidKeyException If the verification key is invalid.
 * @throws SignatureException If signature verification failed.
 * @throws GenericCertificateIntegrityException If the integrity of this
 *         certificate has been compromised.
 */
public synchronized final void verify(final PublicKey verificationKey, final Signature verificationEngine)
        throws NullPointerException, GenericCertificateIsLockedException, PropertyVetoException,
        InvalidKeyException, SignatureException, GenericCertificateIntegrityException {
    // Check parameters.
    if (verificationKey == null)
        throw new NullPointerException("verificationKey");
    if (verificationEngine == null)
        throw new NullPointerException("verificationEngine");

    // Check lock status.
    final PropertyChangeEvent evt = new PropertyChangeEvent(this, "locked", Boolean.valueOf(isLocked()),
            Boolean.TRUE); // NOI18N
    if (isLocked())
        throw new GenericCertificateIsLockedException(evt);

    // Notify vetoable listeners and give them a chance to veto.
    fireVetoableChange(evt);

    try {
        // Init the byte encoded object.
        final byte[] beo = getEncoded().getBytes(XML_CHARSET);

        // Verify the byte encoded object.
        verificationEngine.initVerify(verificationKey);
        verificationEngine.update(beo);
        final byte[] b64ds = Base64.decodeBase64(getSignature().getBytes(BASE64_CHARSET));
        if (!verificationEngine.verify(b64ds))
            throw new GenericCertificateIntegrityException();

        // Reset signature parameters.
        setSignatureAlgorithm(verificationEngine.getAlgorithm());
        setSignatureEncoding(SIGNATURE_ENCODING);
    } catch (UnsupportedEncodingException cannotHappen) {
        throw new AssertionError(cannotHappen);
    }

    // Lock this certificate and notify property change listeners.
    this.locked = true;
    firePropertyChange(evt);
}

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

public void validateQueryString(RoleDescriptorType md, String queryString)
        throws SamlR2SignatureException, SamlR2SignatureValidationException {
    try {//from ww w .  j  a  v a 2s. co  m

        X509Certificate cert = getX509Certificate(md);

        if (cert == null) {
            logger.error("No Certificate found in Metadata " + md.getID());
            throw new SamlR2SignatureException("No Certificate found in Metadata " + md.getID());
        }

        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.isTraceEnabled())
            logger.trace("SAML 2.0 Query string to validate [" + queryString + "]");

        StringTokenizer st = new StringTokenizer(queryString, "&");
        String samlParam;

        String samlRequest = null;
        String samlResponse = null;
        String relayState = null;
        String sigAlg = null;
        String encSig = null;

        while (st.hasMoreTokens()) {
            samlParam = st.nextToken();
            if (samlParam.startsWith("SAMLRequest")) {
                samlRequest = samlParam;
            } else if (samlParam.startsWith("SAMLResponse")) {
                samlResponse = samlParam;
            } else if (samlParam.startsWith("RelayState")) {
                relayState = samlParam;
            } else if (samlParam.startsWith("SigAlg")) {
                sigAlg = samlParam;
            } else if (samlParam.startsWith("Signature")) {
                encSig = samlParam;
            } else {
                // Ignore this token ...
                logger.warn("Non-SAML 2.0 parameter ignored " + samlParam);
            }
        }
        if ((samlRequest == null || samlRequest.equals(""))
                && (samlResponse == null || samlResponse.equals("")))
            throw new SamlR2SignatureValidationException(
                    "SAML 2.0 Query string MUST contain either 'SAMLRequest' or 'SAMLResponse' parameter");

        if (sigAlg == null || sigAlg.equals(""))
            throw new SamlR2SignatureValidationException(
                    "SAML 2.0 Query string MUST contain a 'SigAlg' parameter");

        if (encSig == null || encSig.equals("")) {
            throw new SamlR2SignatureValidationException(
                    "SAML 2.0 Query string MUST contain a 'Signature' parameter");
        }

        // Re-order paramters just in case they were mixed-up while getting here.
        String newQueryString = null;
        if (samlRequest != null) {
            newQueryString = samlRequest;
        } else {
            newQueryString = samlResponse;
        }
        if (relayState != null) {
            newQueryString += "&" + relayState;
        }
        newQueryString += "&" + sigAlg;
        if (logger.isDebugEnabled())
            logger.debug(
                    "SAML 2.0 Query string signature validation for (re-arranged) [" + newQueryString + "]");

        int sigAlgValueIndex = sigAlg.indexOf('=');

        // Get Signature Algorithm
        String sigAlgValue = sigAlg.substring(sigAlgValueIndex + 1);
        if (sigAlgValue == null || sigAlgValue.equals("")) {
            throw new SamlR2SignatureValidationException(
                    "SAML 2.0 Query string MUST contain a 'SigAlg' parameter value");
        }
        sigAlgValue = URLDecoder.decode(sigAlgValue, "UTF-8");
        if (logger.isTraceEnabled())
            logger.trace("SigAlg=" + sigAlgValue);

        // Get Signature value
        int encSigValueIndex = encSig.indexOf('=');
        String signatureEnc = encSig.substring(encSigValueIndex + 1);
        if (signatureEnc == null || signatureEnc.equals("")) {
            throw new SamlR2SignatureValidationException(
                    "SAML 2.0 Query string MUST contain a 'Signature' parameter value");
        }
        signatureEnc = URLDecoder.decode(signatureEnc, "UTF-8");
        if (logger.isTraceEnabled())
            logger.trace("Signature=" + signatureEnc);

        // base-64 decode the signature value
        byte[] signatureBin = null;
        Base64 decoder = new Base64();
        signatureBin = decoder.decode(signatureEnc.getBytes());

        // get Signature instance based on algorithm
        // TODO : Support SHA-256
        Signature signature = null;
        if (sigAlgValue.equals(SignatureMethod.DSA_SHA1)) {
            signature = Signature.getInstance(SHA1_WITH_DSA);
        } else if (sigAlgValue.equals(SignatureMethod.RSA_SHA1)) {
            signature = Signature.getInstance(SHA1_WITH_RSA);
        } else {
            throw new SamlR2SignatureException("SAML 2.0 Siganture does not support algorithm " + sigAlgValue);
        }

        // now verify signature
        signature.initVerify(cert);
        signature.update(newQueryString.getBytes());
        if (!signature.verify(signatureBin)) {
            // TODO : Get information about the error ?!
            throw new SamlR2SignatureValidationException("Invalid digital signature");
        }

        if (!validateCertificate(md, null)) {
            throw new SamlR2SignatureValidationException("Certificate is not valid, check logs for details");
        }

    } catch (Exception e) {
        logger.error("Cannot verify digital SAML 2.0 Query string signature " + e.getMessage(), e);
        throw new SamlR2SignatureException(
                "Cannot verify digital SAML 2.0 Query string signature " + e.getMessage(), e);
    }
}

From source file:org.openbravo.erpCommon.obps.ActivationKey.java

private boolean decrypt(byte[] bytes, PublicKey pk, ByteArrayOutputStream bos, String strOBPublicKey)
        throws Exception {
    PublicKey obPk = getPublicKey(strOBPublicKey); // get OB public key to check signature
    Signature signer = Signature.getInstance("MD5withRSA");
    signer.initVerify(obPk);

    Cipher cipher = Cipher.getInstance("RSA");

    ByteArrayInputStream bis = new ByteArrayInputStream(
            org.apache.commons.codec.binary.Base64.decodeBase64(bytes));

    // Encryptation only accepts 128B size, it must be chuncked
    final byte[] buf = new byte[128];
    final byte[] signature = new byte[128];

    // read the signature
    if (!(bis.read(signature) > 0)) {
        return false;
    }/*from  w w w  . j  a  v a2 s.  c o  m*/

    // decrypt
    while ((bis.read(buf)) > 0) {
        cipher.init(Cipher.DECRYPT_MODE, pk);
        bos.write(cipher.doFinal(buf));
    }

    // verify signature
    signer.update(bos.toByteArray());
    boolean signed = signer.verify(signature);
    log.debug("signature length:" + buf.length);
    log.debug("singature:" + (new BigInteger(signature).toString(16).toUpperCase()));
    log.debug("signed:" + signed);
    if (!signed) {
        isActive = false;
        errorMessage = "@NotSigned@";
        setLogger();
        return false;
    }
    return true;
}

From source file:com.threerings.getdown.data.Application.java

/**
 * Downloads a new copy of the specified control file, optionally validating its signature.
 * If the download is successful, moves it over the old file on the filesystem.
 *
 * <p> We implement simple signing of the digest.txt file for use with the Getdown applet, but
 * this should never be used as-is with a non-applet getdown installation, as the signing
 * format has no provisions for declaring arbitrary signing key IDs, signature algorithm, et al
 * -- it is entirely reliant on the ability to upgrade the Getdown applet, and its signature
 * validation implementation, at-will (ie, via an Applet).
 *
 * <p> TODO: Switch to PKCS #7 or CMS.
 *///  w  ww  .j  ava 2s .  c o  m
protected void downloadControlFile(String path, boolean validateSignature) throws IOException {
    File target = downloadFile(path);

    if (validateSignature) {
        if (_signers.isEmpty()) {
            log.info("No signers, not verifying file", "path", path);

        } else {
            File signatureFile = downloadFile(path + SIGNATURE_SUFFIX);
            byte[] signature = null;
            FileReader reader = null;
            try {
                reader = new FileReader(signatureFile);
                signature = StreamUtil.toByteArray(new FileInputStream(signatureFile));
            } finally {
                StreamUtil.close(reader);
                signatureFile.delete(); // delete the file regardless
            }

            byte[] buffer = new byte[8192];
            int length, validated = 0;
            for (Certificate cert : _signers) {
                FileInputStream dataInput = null;
                try {
                    dataInput = new FileInputStream(target);
                    Signature sig = Signature.getInstance("SHA1withRSA");
                    sig.initVerify(cert);
                    while ((length = dataInput.read(buffer)) != -1) {
                        sig.update(buffer, 0, length);
                    }

                    if (!sig.verify(Base64.decodeBase64(signature))) {
                        log.info("Signature does not match", "cert", cert.getPublicKey());
                        continue;
                    } else {
                        log.info("Signature matches", "cert", cert.getPublicKey());
                        validated++;
                    }

                } catch (IOException ioe) {
                    log.warning("Failure validating signature of " + target + ": " + ioe);

                } catch (GeneralSecurityException gse) {
                    // no problem!

                } finally {
                    StreamUtil.close(dataInput);
                    dataInput = null;
                }
            }

            // if we couldn't find a key that validates our digest, we are the hosed!
            if (validated == 0) {
                // delete the temporary digest file as we know it is invalid
                target.delete();
                throw new IOException("m.corrupt_digest_signature_error");
            }
        }
    }

    // now move the temporary file over the original
    File original = getLocalPath(path);
    if (!FileUtil.renameTo(target, original)) {
        throw new IOException("Failed to rename(" + target + ", " + original + ")");
    }
}

From source file:org.apache.geode.internal.cache.tier.sockets.HandShake.java

/**
 * This assumes that authentication is the last piece of info in handshake
 *//*from ww w. ja v a 2 s.  c  o  m*/
public void writeCredentials(DataOutputStream dos, DataInputStream dis, Properties p_credentials,
        boolean isNotification, DistributedMember member, HeapDataOutputStream heapdos)
        throws IOException, GemFireSecurityException {

    if (p_credentials == null) {
        // No credentials indicator
        heapdos.writeByte(CREDENTIALS_NONE);
        heapdos.flush();
        dos.write(heapdos.toByteArray());
        dos.flush();
        return;
    }

    if (dhSKAlgo == null || dhSKAlgo.length() == 0) {
        // Normal credentials without encryption indicator
        heapdos.writeByte(CREDENTIALS_NORMAL);
        DataSerializer.writeProperties(p_credentials, heapdos);
        heapdos.flush();
        dos.write(heapdos.toByteArray());
        dos.flush();
        return;
    }

    try {
        InternalLogWriter securityLogWriter = (InternalLogWriter) this.system.getSecurityLogWriter();
        securityLogWriter.fine("HandShake: using Diffie-Hellman key exchange with algo " + dhSKAlgo);
        boolean requireAuthentication = (certificateFilePath != null && certificateFilePath.length() > 0);
        if (requireAuthentication) {
            securityLogWriter.fine("HandShake: server authentication using digital " + "signature required");
        }
        // Credentials with encryption indicator
        heapdos.writeByte(CREDENTIALS_DHENCRYPT);
        heapdos.writeBoolean(requireAuthentication);
        // Send the symmetric encryption algorithm name
        DataSerializer.writeString(dhSKAlgo, heapdos);
        // Send the DH public key
        byte[] keyBytes = dhPublicKey.getEncoded();
        DataSerializer.writeByteArray(keyBytes, heapdos);
        byte[] clientChallenge = null;
        if (requireAuthentication) {
            // Authentication of server should be with the client supplied
            // challenge
            clientChallenge = new byte[64];
            random.nextBytes(clientChallenge);
            DataSerializer.writeByteArray(clientChallenge, heapdos);
        }
        heapdos.flush();
        dos.write(heapdos.toByteArray());
        dos.flush();

        // Expect the alias and signature in the reply
        byte acceptanceCode = dis.readByte();
        if (acceptanceCode != REPLY_OK && acceptanceCode != REPLY_AUTH_NOT_REQUIRED) {
            // Ignore the useless data
            dis.readByte();
            dis.readInt();
            if (!isNotification) {
                DataSerializer.readByteArray(dis);
            }
            readMessage(dis, dos, acceptanceCode, member);
        } else if (acceptanceCode == REPLY_OK) {
            // Get the public key of the other side
            keyBytes = DataSerializer.readByteArray(dis);
            if (requireAuthentication) {
                String subject = DataSerializer.readString(dis);
                byte[] signatureBytes = DataSerializer.readByteArray(dis);
                if (!certificateMap.containsKey(subject)) {
                    throw new AuthenticationFailedException(
                            LocalizedStrings.HandShake_HANDSHAKE_FAILED_TO_FIND_PUBLIC_KEY_FOR_SERVER_WITH_SUBJECT_0
                                    .toLocalizedString(subject));
                }

                // Check the signature with the public key
                X509Certificate cert = (X509Certificate) certificateMap.get(subject);
                Signature sig = Signature.getInstance(cert.getSigAlgName());
                sig.initVerify(cert);
                sig.update(clientChallenge);
                // Check the challenge string
                if (!sig.verify(signatureBytes)) {
                    throw new AuthenticationFailedException(
                            "Mismatch in client " + "challenge bytes. Malicious server?");
                }
                securityLogWriter
                        .fine("HandShake: Successfully verified the " + "digital signature from server");
            }

            byte[] challenge = DataSerializer.readByteArray(dis);
            X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
            KeyFactory keyFact = KeyFactory.getInstance("DH");
            // PublicKey pubKey = keyFact.generatePublic(x509KeySpec);
            this.clientPublicKey = keyFact.generatePublic(x509KeySpec);

            HeapDataOutputStream hdos = new HeapDataOutputStream(Version.CURRENT);
            try {
                DataSerializer.writeProperties(p_credentials, hdos);
                // Also add the challenge string
                DataSerializer.writeByteArray(challenge, hdos);

                // byte[] encBytes = encrypt.doFinal(hdos.toByteArray());
                byte[] encBytes = encryptBytes(hdos.toByteArray(),
                        getEncryptCipher(dhSKAlgo, this.clientPublicKey));
                DataSerializer.writeByteArray(encBytes, dos);
            } finally {
                hdos.close();
            }
        }
    } catch (IOException ex) {
        throw ex;
    } catch (GemFireSecurityException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new AuthenticationFailedException("HandShake failed in Diffie-Hellman key exchange", ex);
    }
    dos.flush();
}

From source file:org.apache.geode.internal.cache.tier.sockets.HandShake.java

/**
 * This method writes what readCredential() method expects to read. (Note the use of singular
 * credential). It is similar to writeCredentials(), except that it doesn't write
 * credential-properties.//from ww w.j  a va 2 s . c om
 */
public byte writeCredential(DataOutputStream dos, DataInputStream dis, String authInit, boolean isNotification,
        DistributedMember member, HeapDataOutputStream heapdos) throws IOException, GemFireSecurityException {

    if (!this.multiuserSecureMode && (authInit == null || authInit.length() == 0)) {
        // No credentials indicator
        heapdos.writeByte(CREDENTIALS_NONE);
        heapdos.flush();
        dos.write(heapdos.toByteArray());
        dos.flush();
        return -1;
    }

    if (dhSKAlgo == null || dhSKAlgo.length() == 0) {
        // Normal credentials without encryption indicator
        heapdos.writeByte(CREDENTIALS_NORMAL);
        this.appSecureMode = CREDENTIALS_NORMAL;
        // DataSerializer.writeProperties(p_credentials, heapdos);
        heapdos.flush();
        dos.write(heapdos.toByteArray());
        dos.flush();
        return -1;
    }
    byte acceptanceCode = -1;
    try {
        InternalLogWriter securityLogWriter = (InternalLogWriter) this.system.getSecurityLogWriter();
        securityLogWriter.fine("HandShake: using Diffie-Hellman key exchange with algo " + dhSKAlgo);
        boolean requireAuthentication = (certificateFilePath != null && certificateFilePath.length() > 0);
        if (requireAuthentication) {
            securityLogWriter.fine("HandShake: server authentication using digital " + "signature required");
        }
        // Credentials with encryption indicator
        heapdos.writeByte(CREDENTIALS_DHENCRYPT);
        this.appSecureMode = CREDENTIALS_DHENCRYPT;
        heapdos.writeBoolean(requireAuthentication);
        // Send the symmetric encryption algorithm name
        DataSerializer.writeString(dhSKAlgo, heapdos);
        // Send the DH public key
        byte[] keyBytes = dhPublicKey.getEncoded();
        DataSerializer.writeByteArray(keyBytes, heapdos);
        byte[] clientChallenge = null;
        if (requireAuthentication) {
            // Authentication of server should be with the client supplied
            // challenge
            clientChallenge = new byte[64];
            random.nextBytes(clientChallenge);
            DataSerializer.writeByteArray(clientChallenge, heapdos);
        }
        heapdos.flush();
        dos.write(heapdos.toByteArray());
        dos.flush();

        // Expect the alias and signature in the reply
        acceptanceCode = dis.readByte();
        if (acceptanceCode != REPLY_OK && acceptanceCode != REPLY_AUTH_NOT_REQUIRED) {
            // Ignore the useless data
            dis.readByte();
            dis.readInt();
            if (!isNotification) {
                DataSerializer.readByteArray(dis);
            }
            readMessage(dis, dos, acceptanceCode, member);
        } else if (acceptanceCode == REPLY_OK) {
            // Get the public key of the other side
            keyBytes = DataSerializer.readByteArray(dis);
            if (requireAuthentication) {
                String subject = DataSerializer.readString(dis);
                byte[] signatureBytes = DataSerializer.readByteArray(dis);
                if (!certificateMap.containsKey(subject)) {
                    throw new AuthenticationFailedException(
                            LocalizedStrings.HandShake_HANDSHAKE_FAILED_TO_FIND_PUBLIC_KEY_FOR_SERVER_WITH_SUBJECT_0
                                    .toLocalizedString(subject));
                }

                // Check the signature with the public key
                X509Certificate cert = (X509Certificate) certificateMap.get(subject);
                Signature sig = Signature.getInstance(cert.getSigAlgName());
                sig.initVerify(cert);
                sig.update(clientChallenge);
                // Check the challenge string
                if (!sig.verify(signatureBytes)) {
                    throw new AuthenticationFailedException(
                            "Mismatch in client " + "challenge bytes. Malicious server?");
                }
                securityLogWriter
                        .fine("HandShake: Successfully verified the " + "digital signature from server");
            }

            // Read server challenge bytes
            byte[] serverChallenge = DataSerializer.readByteArray(dis);
            X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
            KeyFactory keyFact = KeyFactory.getInstance("DH");
            // PublicKey pubKey = keyFact.generatePublic(x509KeySpec);
            this.clientPublicKey = keyFact.generatePublic(x509KeySpec);

            HeapDataOutputStream hdos = new HeapDataOutputStream(Version.CURRENT);
            try {
                // Add the challenge string
                DataSerializer.writeByteArray(serverChallenge, hdos);
                // byte[] encBytes = encrypt.doFinal(hdos.toByteArray());
                byte[] encBytes = encryptBytes(hdos.toByteArray(),
                        getEncryptCipher(dhSKAlgo, this.clientPublicKey));
                DataSerializer.writeByteArray(encBytes, dos);
            } finally {
                hdos.close();
            }
        }
    } catch (IOException ex) {
        throw ex;
    } catch (GemFireSecurityException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new AuthenticationFailedException("HandShake failed in Diffie-Hellman key exchange", ex);
    }
    dos.flush();
    return acceptanceCode;
}

From source file:org.ejbca.core.protocol.cmp.CrmfKeyUpdateTest.java

/**
 * Sends a KeyUpdateRequest with a different key and the configurations is NOT to allow the use of the same keys. 
 * Successful operation is expected and a new certificate is received.
 * // www  .  j ava  2 s .  c  om
 * - Pre-configuration: Sets the operational mode to client mode (cmp.raoperationalmode=normal)
 * - Pre-configuration: Sets cmp.allowautomaticrenewal to 'true' and tests that the resetting of configuration has worked.
 * - Pre-configuration: Sets cmp.allowupdatewithsamekey to 'false'
 * - Creates a new user and obtains a certificate, cert, for this user. Tests whether obtaining the certificate was successful.
 * - Generates a CMP KeyUpdate Request and tests that such request has been created.
 * - Signs the CMP request using cert and attaches cert to the CMP request. Tests that the CMP request is still not null
 * - Sends the request using HTTP and receives a response.
 * - Examines the response:
 *       - Checks that the response is not empty or null
 *       - Checks that the protection algorithm is sha1WithRSAEncryption
 *       - Check that the signer is the expected CA
 *       - Verifies the response signature
 *       - Checks that the response's senderNonce is 16 bytes long
 *       - Checks that the request's senderNonce is the same as the response's recipientNonce
 *       - Checks that the request and the response has the same transactionID
 *       - Obtains the certificate from the response
 *       - Checks that the obtained certificate has the right subjectDN and issuerDN
 * 
 * @throws Exception
 */
@Test
public void test06UpdateWithDifferentKey() throws Exception {
    if (log.isTraceEnabled()) {
        log.trace(">test08UpdateWithDifferentKey");
    }

    this.cmpConfiguration.setRAMode(this.cmpAlias, false);
    this.cmpConfiguration.setKurAllowAutomaticUpdate(this.cmpAlias, true);
    this.cmpConfiguration.setKurAllowSameKey(this.cmpAlias, false);
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    //--------------- create the user and issue his first certificate -----------------
    createUser(this.username, this.userDN.toString(), "foo123");
    KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
    final Certificate certificate;
    certificate = this.signSession.createCertificate(ADMIN, this.username, "foo123",
            new PublicKeyWrapper(keys.getPublic()));
    assertNotNull("Failed to create a test certificate", certificate);

    KeyPair newkeys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
    AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
    PKIMessage req = genRenewalReq(this.userDN, this.cacert, this.nonce, this.transid, newkeys, false, null,
            null, pAlg, new DEROctetString(this.nonce));
    assertNotNull("Failed to generate a CMP renewal request", req);
    CertReqMessages kur = (CertReqMessages) req.getBody().getContent();
    int reqId = kur.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();

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

    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(req);
    byte[] ba = bao.toByteArray();
    // Send request and receive response
    byte[] resp = sendCmpHttp(ba, 200, this.cmpAlias);
    checkCmpResponseGeneral(resp, this.issuerDN, this.userDN, this.cacert, this.nonce, this.transid, true, null,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    X509Certificate cert = checkKurCertRepMessage(this.userDN, this.cacert, resp, reqId);
    assertNotNull("Failed to renew the certificate", cert);
    assertTrue("The new certificate's keys are incorrect.", cert.getPublicKey().equals(newkeys.getPublic()));
    assertFalse("The new certificate's keys are the same as the old certificate's keys.",
            cert.getPublicKey().equals(keys.getPublic()));

    if (log.isTraceEnabled()) {
        log.trace("<test08UpdateWithDifferentKey");
    }
}

From source file:org.ejbca.core.protocol.cmp.AuthenticationModulesTest.java

@Test
public void test08EECrmfReqMultipleAuthModules()
        throws NoSuchAlgorithmException, EjbcaException, IOException, Exception {
    String modules = CmpConfiguration.AUTHMODULE_HMAC + ";" + CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE;
    String parameters = "foo123" + ";" + "TestCA";
    this.cmpConfiguration.setAuthenticationModule(ALIAS, modules);
    this.cmpConfiguration.setAuthenticationParameters(ALIAS, parameters);
    this.cmpConfiguration.setRAMode(ALIAS, true);
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);

    AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
    PKIMessage msg = genCertReq(issuerDN, USER_DN, keys, this.cacert, this.nonce, this.transid, false, null,
            null, null, null, pAlg, null);
    assertNotNull("Generating CrmfRequest failed.", msg);

    String adminName = "cmpTestAdmin";
    KeyPair admkeys = KeyTools.genKeys("1024", "RSA");
    AuthenticationToken adminToken = createAdminToken(admkeys, adminName, "CN=" + adminName + ",C=SE",
            this.caid, SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
    Certificate admCert = getCertFromCredentials(adminToken);
    CMPCertificate[] extraCert = getCMPCert(admCert);
    msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, admkeys.getPrivate(),
            pAlg.getAlgorithm().getId(), "BC");
    assertNotNull(msg);/*from   ww w  .jav a2 s.c  o  m*/

    //********************************************
    final Signature sig = Signature.getInstance(msg.getHeader().getProtectionAlg().getAlgorithm().getId(),
            "BC");
    sig.initVerify(admCert.getPublicKey());
    sig.update(CmpMessageHelper.getProtectedBytes(msg));
    boolean verified = sig.verify(msg.getProtection().getBytes());
    assertTrue("Signing the message failed.", verified);
    //********************************************

    final ByteArrayOutputStream bao = new ByteArrayOutputStream();
    final DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(msg);
    final byte[] ba = bao.toByteArray();
    // Send request and receive response
    final byte[] resp = sendCmpHttp(ba, 200, ALIAS);
    checkCmpResponseGeneral(resp, issuerDN, USER_DN, this.cacert, msg.getHeader().getSenderNonce().getOctets(),
            msg.getHeader().getTransactionID().getOctets(), true, null,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    CertReqMessages ir = (CertReqMessages) msg.getBody().getContent();
    Certificate cert2 = checkCmpCertRepMessage(USER_DN, this.cacert, resp,
            ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue());
    assertNotNull("CrmfRequest did not return a certificate", cert2);

    removeAuthenticationToken(adminToken, admCert, adminName);
}