List of usage examples for java.security Signature update
public final void update(ByteBuffer data) throws SignatureException
From source file:be.fedict.eid.dss.protocol.simple.client.SignatureResponseProcessor.java
private void verifyServiceSignature(String serviceSigned, String target, String signatureRequest, String signatureRequestId, String signatureResponse, String signatureResponseId, String encodedSignatureCertificate, byte[] serviceSignatureValue, List<X509Certificate> serviceCertificateChain) throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, SignatureException { LOG.debug("verifying service signature"); X509Certificate serviceCertificate = serviceCertificateChain.get(0); LOG.debug("service identity: " + serviceCertificate.getSubjectX500Principal()); Signature serviceSignature = Signature.getInstance("SHA1withRSA"); serviceSignature.initVerify(serviceCertificate); StringTokenizer serviceSignedStringTokenizer = new StringTokenizer(serviceSigned, ","); while (serviceSignedStringTokenizer.hasMoreTokens()) { String serviceSignedElement = serviceSignedStringTokenizer.nextToken(); LOG.debug("service signed: " + serviceSignedElement); byte[] data; if ("target".equals(serviceSignedElement)) { data = target.getBytes();/*from ww w. ja v a2s. co m*/ } else if ("SignatureRequest".equals(serviceSignedElement)) { data = signatureRequest.getBytes(); } else if ("SignatureRequestId".equals(serviceSignedElement)) { data = signatureRequestId.getBytes(); } else if ("SignatureResponse".equals(serviceSignedElement)) { data = signatureResponse.getBytes(); } else if ("SignatureResponseId".equals(serviceSignedElement)) { data = signatureResponseId.getBytes(); } else if ("SignatureCertificate".equals(serviceSignedElement)) { data = encodedSignatureCertificate.getBytes(); } else { throw new SecurityException("service signed unknown element: " + serviceSignedElement); } serviceSignature.update(data); } boolean valid = serviceSignature.verify(serviceSignatureValue); if (!valid) { throw new SecurityException("service signature not valid"); } if (null != this.serviceFingerprint) { LOG.debug("checking service fingerprint"); byte[] actualServiceFingerprint = DigestUtils.sha(serviceCertificate.getEncoded()); if (!Arrays.equals(this.serviceFingerprint, actualServiceFingerprint)) { throw new SecurityException("service certificate fingerprint mismatch"); } } }
From source file:org.globus.myproxy.MyProxy.java
private InputStream handleReply(InputStream in, OutputStream out, GSSCredential authzcreds, boolean wantTrustroots) throws IOException, MyProxyException { String tmp = null;// w w w .j a v a 2 s .com /* there was something weird here with the received protocol version sometimes. it contains an extra <32 byte. fixed it by using endsWith. now i read extra byte at the end of each message. */ // protocol version tmp = readLine(in); if (tmp == null) { throw new EOFException(); } if (!tmp.endsWith(MyProxyConstants.VERSION)) { throw new MyProxyException("Protocol version mismatch: " + tmp); } // response tmp = readLine(in); if (tmp == null) { throw new EOFException(); } if (!tmp.startsWith(RESPONSE)) { throw new MyProxyException("Invalid reply: no response message"); } boolean error = tmp.charAt(RESPONSE.length()) == '1'; boolean authzchallenge = tmp.charAt(RESPONSE.length()) == '2'; if (error) { StringBuffer errorStr = new StringBuffer(); while ((tmp = readLine(in)) != null) { if (tmp.startsWith(ERROR)) { if (errorStr.length() > 0) errorStr.append(' '); errorStr.append(tmp.substring(ERROR.length())); } } if (errorStr.length() == 0) { errorStr.append("unspecified server error"); } throw new MyProxyException(errorStr.toString()); } if (authzchallenge) { if (authzcreds == null) { throw new MyProxyException( "Unable to respond to server's authentication challenge. No credentials for renewal."); } if (out == null) { throw new MyProxyException("Internal error. Authz challenge but no OutputStream."); } String[] authzdata = null; while ((tmp = readLine(in)) != null) { if (tmp.startsWith(AUTHZ_DATA)) { int pos = tmp.indexOf(':', AUTHZ_DATA.length() + 1); if (pos != -1) { authzdata = new String[2]; authzdata[0] = tmp.substring(AUTHZ_DATA.length(), pos).trim(); authzdata[1] = tmp.substring(pos + 1).trim(); } if (authzdata == null) { throw new MyProxyException("Unable to parse authorization challenge from server."); } if (authzdata[0].equals("X509_certificate")) { GlobusGSSCredentialImpl pkiCred = (GlobusGSSCredentialImpl) authzcreds; try { Signature sig = Signature.getInstance("SHA1withRSA"); sig.initSign(pkiCred.getPrivateKey()); sig.update(authzdata[1].getBytes()); byte[] sigbytes = sig.sign(); X509Certificate[] certs = pkiCred.getCertificateChain(); ByteArrayOutputStream buffer = new ByteArrayOutputStream(2048); buffer.write(2); // AUTHORIZETYPE_CERT buffer.write(0); buffer.write(0); buffer.write(0); // pad DataOutputStream dos = new DataOutputStream(buffer); dos.writeInt(sigbytes.length); dos.flush(); buffer.write(sigbytes); buffer.write((byte) certs.length); for (int i = 0; i < certs.length; i++) { buffer.write(certs[i].getEncoded()); } out.write(buffer.toByteArray()); out.flush(); } catch (Exception e) { throw new MyProxyException("Authz response failed.", e); } } else { authzdata = null; continue; } } } return handleReply(in, out, authzcreds, wantTrustroots); } if (wantTrustroots == true) { while ((tmp = readLine(in)) != null) { if (tmp.startsWith(TRUSTROOTS)) { String filenameList = tmp.substring(TRUSTROOTS.length()); this.trustrootFilenames = filenameList.split(","); this.trustrootData = new String[this.trustrootFilenames.length]; for (int i = 0; i < this.trustrootFilenames.length; i++) { String lineStart = "FILEDATA_" + this.trustrootFilenames[i] + "="; tmp = readLine(in); if (tmp == null) { throw new EOFException(); } if (!tmp.startsWith(lineStart)) { throw new MyProxyException("bad MyProxy protocol RESPONSE: expecting " + lineStart + " but received " + tmp); } this.trustrootData[i] = new String( Base64.decode(tmp.substring(lineStart.length()).getBytes())); } } } } /* always consume the entire message */ int avail = in.available(); byte[] b = new byte[avail]; if (avail > 0) in.read(b); ByteArrayInputStream inn = new ByteArrayInputStream(b); return inn; }
From source file:de.schlichtherle.xml.GenericCertificate.java
/** * //from w w w. j a va 2 s . co m * 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:com.tremolosecurity.proxy.auth.SAML2Auth.java
public void initializeSSO(HttpServletRequest req, HttpServletResponse resp, HttpSession session, boolean isJump, String jumpPage) throws MalformedURLException, ServletException { {/*from w w w . ja v a2s.c o m*/ RequestHolder reqHolder = ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).getHolder(); HashMap<String, Attribute> authParams = (HashMap<String, Attribute>) session .getAttribute(ProxyConstants.AUTH_MECH_PARAMS); boolean isMultiIdp = authParams.get("isMultiIdP") != null && authParams.get("isMultiIdP").getValues().get(0).equalsIgnoreCase("true"); String postAuthnReqTo = ""; String redirAuthnReqTo = ""; String assertionConsumerServiceURL = ""; boolean signAuthnReq = false; String uri = (String) req.getAttribute(ProxyConstants.AUTH_REDIR_URI); if (uri == null) { uri = req.getRequestURI(); } if (isMultiIdp) { URL url = new URL(req.getRequestURL().toString()); String hostName = url.getHost(); String dn = authParams.get("idpDir").getValues().get(0); try { StringBuffer b = new StringBuffer(); LDAPSearchResults res = cfgMgr.getMyVD().search(dn, 2, equal("hostname", hostName).toString(), new ArrayList<String>()); if (!res.hasMore()) { throw new ServletException("No IdP found"); } LDAPEntry entry = res.next(); postAuthnReqTo = entry.getAttribute("idpURL").getStringValue(); redirAuthnReqTo = entry.getAttribute("idpRedirURL").getStringValue(); assertionConsumerServiceURL = ProxyTools.getInstance().getFqdnUrl(uri, req); signAuthnReq = entry.getAttribute("signAuthnReq").getStringValue().equalsIgnoreCase("1"); } catch (LDAPException e) { throw new ServletException("Could not load IdP data", e); } } else { postAuthnReqTo = authParams.get("idpURL").getValues().get(0);// "http://idp.partner.domain.com:8080/opensso/SSOPOST/metaAlias/testSaml2Idp"; redirAuthnReqTo = authParams.get("idpRedirURL").getValues().get(0); assertionConsumerServiceURL = ProxyTools.getInstance().getFqdnUrl(uri, req);// "http://sp.localdomain.com:8080/SampleSP/echo"; if (authParams.get("forceToSSL") != null && authParams.get("forceToSSL").getValues().get(0).equalsIgnoreCase("true")) { if (!assertionConsumerServiceURL.startsWith("https")) { assertionConsumerServiceURL = assertionConsumerServiceURL.replace("http://", "https://"); } } signAuthnReq = authParams.get("signAuthnReq") != null && authParams.get("signAuthnReq").getValues().get(0).equalsIgnoreCase("true"); } ConfigManager cfg = (ConfigManager) req.getAttribute(ProxyConstants.TREMOLO_CFG_OBJ); AuthnRequestBuilder authnBuilder = new AuthnRequestBuilder(); AuthnRequest authn = authnBuilder.buildObject(); authn.setAssertionConsumerServiceURL(assertionConsumerServiceURL); authn.setProtocolBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"); //authn.setDestination(postAuthnReqTo); authn.setDestination(redirAuthnReqTo); DateTime dt = new DateTime(); String authMechanism = authParams.get("authCtxRef").getValues().get(0); byte[] idBytes = new byte[20]; random.nextBytes(idBytes); /*StringBuffer id = new StringBuffer(); for (byte b : idBytes) { id.append(Hex.encode(idBytes)); }*/ StringBuffer b = new StringBuffer(); b.append('f').append(Hex.encodeHexString(idBytes)); String id = b.toString(); authn.setIssueInstant(dt); //authn.setID(Long.toString(random.nextLong())); authn.setID(id.toString()); session.setAttribute("AUTOIDM_SAML2_REQUEST", authn.getID()); IssuerBuilder ib = new IssuerBuilder(); Issuer issuer = ib.buildObject(); issuer.setValue(assertionConsumerServiceURL); authn.setIssuer(issuer); //authn.setAssertionConsumerServiceIndex(0); //authn.setAttributeConsumingServiceIndex(0); NameIDPolicyBuilder nidbpb = new NameIDPolicyBuilder(); NameIDPolicy nidp = nidbpb.buildObject(); //nidp.setFormat("urn:oasis:names:tc:SAML:2.0:nameid-format:unspecified"); nidp.setFormat("urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"); nidp.setAllowCreate(true); nidp.setSPNameQualifier(assertionConsumerServiceURL); //authn.setNameIDPolicy(nidp); authn.setIsPassive(false); //authn.setProviderName("tremolosecurity.com"); if (!authMechanism.isEmpty() && !authMechanism.equalsIgnoreCase("none")) { AuthnContextClassRefBuilder accrb = new AuthnContextClassRefBuilder(); AuthnContextClassRef accr = accrb.buildObject(); accr.setAuthnContextClassRef(authMechanism); //accr.setAuthnContextClassRef("urn:federation:authentication:windows"); //accr.setAuthnContextClassRef("urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport"); RequestedAuthnContextBuilder racb = new RequestedAuthnContextBuilder(); RequestedAuthnContext rac = racb.buildObject(); rac.getAuthnContextClassRefs().add(accr); rac.setComparison(AuthnContextComparisonTypeEnumeration.EXACT); authn.setRequestedAuthnContext(rac); } authn.setForceAuthn(false); try { // Get the Subject marshaller Marshaller marshaller = new AuthnRequestMarshaller(); // Marshall the Subject //Element assertionElement = marshaller.marshall(authn); String xml = OpenSAMLUtils.xml2str(authn); xml = xml.substring(xml.indexOf("?>") + 2); if (logger.isDebugEnabled()) { logger.debug("=======AuthnRequest============"); logger.debug(xml); logger.debug("=======AuthnRequest============"); } byte[] bxml = xml.getBytes("UTF-8"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); DeflaterOutputStream compressor = new DeflaterOutputStream(baos, new Deflater(Deflater.BEST_COMPRESSION, true)); compressor.write(bxml); compressor.flush(); compressor.close(); String b64 = new String(Base64.encodeBase64(baos.toByteArray())); StringBuffer redirURL = new StringBuffer(); StringBuffer query = new StringBuffer(); idBytes = new byte[20]; random.nextBytes(idBytes); query.append("SAMLRequest=").append(URLEncoder.encode(b64, "UTF-8")).append("&RelayState=") .append(URLEncoder.encode(Hex.encodeHexString(idBytes), "UTF-8")); if (signAuthnReq) { String sigAlg = authParams.get("sigAlg") != null ? authParams.get("sigAlg").getValues().get(0) : "RSA-SHA1"; String xmlSigAlg = SAML2Auth.xmlDigSigAlgs.get(sigAlg); String javaSigAlg = SAML2Auth.javaDigSigAlgs.get(sigAlg); //sb.append("SAMLRequest=").append(xml).append("&SigAlg=").append(URLEncoder.encode("http://www.w3.org/2000/09/xmldsig#rsa-sha1", "UTF-8")); query.append("&SigAlg=").append(URLEncoder.encode(xmlSigAlg, "UTF-8")); java.security.Signature signer = java.security.Signature.getInstance(javaSigAlg); if (authParams.get("spSigKey") == null) { throw new ServletException("No signature certificate specified"); } String spSigKey = authParams.get("spSigKey").getValues().get(0); signer.initSign(cfgMgr.getPrivateKey(spSigKey)); signer.update(query.toString().getBytes("UTF-8")); String base64Sig = new String(Base64.encodeBase64(signer.sign())); query.append("&Signature=").append(URLEncoder.encode(base64Sig, "UTF-8")); } redirURL.append(redirAuthnReqTo).append("?").append(query.toString()); if (isJump) { if (logger.isDebugEnabled()) { logger.debug("Redirecting to Jump Page"); logger.debug("SAML2_JUMPPAGE='" + req.getAttribute("TREMOLO_AUTH_REDIR_URI")); } session.setAttribute("SAML2_JUMPPAGE", redirURL.toString()); resp.sendRedirect(jumpPage); } else { resp.sendRedirect(redirURL.toString()); } /*String b64 = new String( org.apache.directory.shared.ldap.util.Base64 .encode(bxml)); req.setAttribute("postaction", postAuthnReqTo); req.setAttribute("postdata", b64); req.getRequestDispatcher("/auth/fed/postauthnreq.jsp").forward( req, resp);*/ } catch (Exception e) { throw new ServletException("Error generating new authn request", e); } } }
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 w w w . j a v a2 s. c om 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.apache.geode.internal.cache.tier.sockets.HandShake.java
/** * This assumes that authentication is the last piece of info in handshake *//* w ww.ja va 2s .co 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.// w w w .j a v a 2 s. co m */ 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.apache.geode.internal.cache.tier.sockets.HandShake.java
public Properties readCredential(DataInputStream dis, DataOutputStream dos, DistributedSystem system) throws GemFireSecurityException, IOException { Properties credentials = null; boolean requireAuthentication = securityService.isClientSecurityRequired(); try {// w w w . j a v a 2 s .co m byte secureMode = dis.readByte(); throwIfMissingRequiredCredentials(requireAuthentication, secureMode != CREDENTIALS_NONE); if (secureMode == CREDENTIALS_NORMAL) { this.appSecureMode = CREDENTIALS_NORMAL; /* * if (requireAuthentication) { credentials = DataSerializer.readProperties(dis); } else { * DataSerializer.readProperties(dis); // ignore the credentials } */ } else if (secureMode == CREDENTIALS_DHENCRYPT) { this.appSecureMode = CREDENTIALS_DHENCRYPT; boolean sendAuthentication = dis.readBoolean(); InternalLogWriter securityLogWriter = (InternalLogWriter) system.getSecurityLogWriter(); // Get the symmetric encryption algorithm to be used // String skAlgo = DataSerializer.readString(dis); this.clientSKAlgo = DataSerializer.readString(dis); // Get the public key of the other side byte[] keyBytes = DataSerializer.readByteArray(dis); byte[] challenge = null; // PublicKey pubKey = null; if (requireAuthentication) { // Generate PublicKey from encoded form X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFact = KeyFactory.getInstance("DH"); this.clientPublicKey = keyFact.generatePublic(x509KeySpec); // Send the public key to other side keyBytes = dhPublicKey.getEncoded(); challenge = new byte[64]; random.nextBytes(challenge); // If the server has to also authenticate itself then // sign the challenge from client. if (sendAuthentication) { // Get the challenge string from client byte[] clientChallenge = DataSerializer.readByteArray(dis); if (privateKeyEncrypt == null) { throw new AuthenticationFailedException( LocalizedStrings.HandShake_SERVER_PRIVATE_KEY_NOT_AVAILABLE_FOR_CREATING_SIGNATURE .toLocalizedString()); } // Sign the challenge from client and send it to the client Signature sig = Signature.getInstance(privateKeySignAlgo); sig.initSign(privateKeyEncrypt); sig.update(clientChallenge); byte[] signedBytes = sig.sign(); dos.writeByte(REPLY_OK); DataSerializer.writeByteArray(keyBytes, dos); // DataSerializer.writeString(privateKeyAlias, dos); DataSerializer.writeString(privateKeySubject, dos); DataSerializer.writeByteArray(signedBytes, dos); securityLogWriter.fine("HandShake: sent the signed client challenge"); } else { // These two lines should not be moved before the if{} statement in // a common block for both if...then...else parts. This is to handle // the case when an AuthenticationFailedException is thrown by the // if...then part when sending the signature. dos.writeByte(REPLY_OK); DataSerializer.writeByteArray(keyBytes, dos); } // Now send the server challenge DataSerializer.writeByteArray(challenge, dos); securityLogWriter.fine("HandShake: sent the public key and challenge"); dos.flush(); // Read and decrypt the credentials byte[] encBytes = DataSerializer.readByteArray(dis); Cipher c = getDecryptCipher(this.clientSKAlgo, this.clientPublicKey); byte[] credentialBytes = decryptBytes(encBytes, c); ByteArrayInputStream bis = new ByteArrayInputStream(credentialBytes); DataInputStream dinp = new DataInputStream(bis); // credentials = DataSerializer.readProperties(dinp);//Hitesh: we don't send in handshake // now byte[] challengeRes = DataSerializer.readByteArray(dinp); // Check the challenge string if (!Arrays.equals(challenge, challengeRes)) { throw new AuthenticationFailedException( LocalizedStrings.HandShake_MISMATCH_IN_CHALLENGE_BYTES_MALICIOUS_CLIENT .toLocalizedString()); } dinp.close(); } else { if (sendAuthentication) { // Read and ignore the client challenge DataSerializer.readByteArray(dis); } dos.writeByte(REPLY_AUTH_NOT_REQUIRED); dos.flush(); } } } catch (IOException ex) { throw ex; } catch (GemFireSecurityException ex) { throw ex; } catch (Exception ex) { throw new AuthenticationFailedException( LocalizedStrings.HandShake_FAILURE_IN_READING_CREDENTIALS.toLocalizedString(), ex); } return credentials; }
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 a v a 2 s.com*/ * - 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 www.ja v a 2s . 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); }