List of usage examples for java.security Signature initSign
public final void initSign(PrivateKey privateKey) throws InvalidKeyException
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;/*from ww w . j a v a 2s .c om*/ /* 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:com.tremolosecurity.proxy.auth.SAML2Auth.java
public void initializeSSO(HttpServletRequest req, HttpServletResponse resp, HttpSession session, boolean isJump, String jumpPage) throws MalformedURLException, ServletException { {// w ww. j ava2s.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.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 {//from w ww. j a v a 2 s . c o 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.atricore.idbus.capabilities.sso.support.core.signature.JSR105SamlR2SignerImpl.java
public String signQueryString(String queryString) throws SamlR2SignatureException { try {/*from w w w . ja v a 2s . c o m*/ if (queryString == null || queryString.length() == 0) { logger.error("SAML 2.0 Qery string null"); throw new SamlR2SignatureException("SAML 2.0 Qery string null"); } if (logger.isDebugEnabled()) logger.debug("Received SAML 2.0 Query string [" + queryString + "] for signing"); PrivateKey privateKey = (PrivateKey) this.getKeyResolver().getPrivateKey(); String keyAlgorithm = privateKey.getAlgorithm(); Signature signature = null; String algURI = null; if (keyAlgorithm.equals("RSA")) { signature = Signature.getInstance(SHA1_WITH_RSA); algURI = SignatureMethod.RSA_SHA1; } else if (keyAlgorithm.equals("DSA")) { signature = Signature.getInstance(SHA1_WITH_DSA); algURI = SignatureMethod.DSA_SHA1; } else { throw new SamlR2SignatureException( "SAML 2.0 Signature does not support provided key's algorithm " + keyAlgorithm); } if (queryString.charAt(queryString.length() - 1) != '&') { queryString = queryString + "&"; } queryString += "SigAlg=" + URLEncoder.encode(algURI, "UTF-8"); if (logger.isTraceEnabled()) logger.trace("Signing SAML 2.0 Query string [" + queryString + "]"); signature.initSign(privateKey); signature.update(queryString.getBytes()); byte[] sigBytes = null; sigBytes = signature.sign(); if (sigBytes == null || sigBytes.length == 0) { logger.error("Cannot generate signed query string, Signature created 'null' value."); throw new SamlR2SignatureException( "Cannot generate signed query string, Signature created 'null' value."); } Base64 encoder = new Base64(); String encodedSig = new String(encoder.encode(sigBytes), "UTF-8"); queryString += "&Signature=" + URLEncoder.encode(encodedSig, "UTF-8"); if (logger.isTraceEnabled()) logger.trace("Signed SAML 2.0 Query string [" + queryString + "]"); return queryString; } catch (Exception e) { throw new SamlR2SignatureException("Error generating SAML 2.0 Query string signature " + e.getMessage(), e); } }
From source file:org.ejbca.core.ejb.ca.caadmin.CAAdminSessionBean.java
@Override public void restoreCAKeyStore(AuthenticationToken authenticationToken, String caname, byte[] p12file, String keystorepass, String privkeypass, String privateSignatureKeyAlias, String privateEncryptionKeyAlias) { if (log.isTraceEnabled()) { log.trace(">restoreCAKeyStore"); }/*w ww .j av a 2s . c o m*/ try { // check authorization if (!accessSession.isAuthorizedNoLogging(authenticationToken, StandardRules.ROLE_ROOT.resource())) { final String detailsMsg = intres.getLocalizedMessage("caadmin.notauthorizedtorestorecatoken", caname); auditSession.log(EventTypes.ACCESS_CONTROL, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE, authenticationToken.toString(), null, null, null, detailsMsg); } CA thisCa = caSession.getCAForEdit(authenticationToken, caname); final CAToken thisCAToken = thisCa.getCAToken(); CryptoToken cryptoToken = cryptoTokenSession.getCryptoToken(thisCAToken.getCryptoTokenId()); if (cryptoToken != null) { throw new Exception("CA already has an existing CryptoToken reference: " + cryptoToken.getId()); } // load keystore from input KeyStore keystore = KeyStore.getInstance("PKCS12", "BC"); keystore.load(new ByteArrayInputStream(p12file), keystorepass.toCharArray()); // Extract signature keys if (privateSignatureKeyAlias == null || !keystore.isKeyEntry(privateSignatureKeyAlias)) { throw new Exception("Alias \"" + privateSignatureKeyAlias + "\" not found."); } Certificate[] signatureCertChain = KeyTools.getCertChain(keystore, privateSignatureKeyAlias); if (signatureCertChain.length < 1) { String msg = "Cannot load certificate chain with alias " + privateSignatureKeyAlias; log.error(msg); throw new Exception(msg); } Certificate caSignatureCertificate = (Certificate) signatureCertChain[0]; PublicKey p12PublicSignatureKey = caSignatureCertificate.getPublicKey(); PrivateKey p12PrivateSignatureKey = null; p12PrivateSignatureKey = (PrivateKey) keystore.getKey(privateSignatureKeyAlias, privkeypass.toCharArray()); // Extract encryption keys PrivateKey p12PrivateEncryptionKey = null; PublicKey p12PublicEncryptionKey = null; Certificate caEncryptionCertificate = null; if (privateEncryptionKeyAlias != null) { if (!keystore.isKeyEntry(privateEncryptionKeyAlias)) { throw new Exception("Alias \"" + privateEncryptionKeyAlias + "\" not found."); } Certificate[] encryptionCertChain = KeyTools.getCertChain(keystore, privateEncryptionKeyAlias); if (encryptionCertChain.length < 1) { String msg = "Cannot load certificate chain with alias " + privateEncryptionKeyAlias; log.error(msg); throw new Exception(msg); } caEncryptionCertificate = (Certificate) encryptionCertChain[0]; p12PrivateEncryptionKey = (PrivateKey) keystore.getKey(privateEncryptionKeyAlias, privkeypass.toCharArray()); p12PublicEncryptionKey = caEncryptionCertificate.getPublicKey(); } else { throw new Exception("Missing encryption key"); } // Sign something to see that we are restoring the right private signature key String testSigAlg = (String) AlgorithmTools .getSignatureAlgorithms(thisCa.getCACertificate().getPublicKey()).iterator().next(); if (testSigAlg == null) { testSigAlg = "SHA1WithRSA"; } // Sign with imported private key byte[] input = "Test data...".getBytes(); Signature signature = Signature.getInstance(testSigAlg, "BC"); signature.initSign(p12PrivateSignatureKey); signature.update(input); byte[] signed = signature.sign(); // Verify with public key from CA certificate signature = Signature.getInstance(testSigAlg, "BC"); signature.initVerify(thisCa.getCACertificate().getPublicKey()); signature.update(input); if (!signature.verify(signed)) { throw new Exception("Could not use private key for verification. Wrong p12-file for this CA?"); } // Import the keys and save to database CAToken catoken = importKeysToCAToken(authenticationToken, keystorepass, thisCAToken.getProperties(), p12PrivateSignatureKey, p12PublicSignatureKey, p12PrivateEncryptionKey, p12PublicEncryptionKey, signatureCertChain, thisCa.getCAId()); thisCa.setCAToken(catoken); // Finally save the CA caSession.editCA(authenticationToken, thisCa, true); // Log final String detailsMsg = intres.getLocalizedMessage("caadmin.restoredcakeystore", Integer.valueOf(thisCa.getCAId())); auditSession.log(EjbcaEventTypes.CA_RESTORETOKEN, EventStatus.SUCCESS, ModuleTypes.CA, ServiceTypes.CORE, authenticationToken.toString(), String.valueOf(thisCa.getCAId()), null, null, detailsMsg); } catch (Exception e) { final String detailsMsg = intres.getLocalizedMessage("caadmin.errorrestorecakeystore", caname, "PKCS12", e.getMessage()); auditSession.log(EjbcaEventTypes.CA_RESTORETOKEN, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE, authenticationToken.toString(), null, null, null, detailsMsg); throw new EJBException(e); } if (log.isTraceEnabled()) { log.trace("<restoreCAKeyStore"); } }
From source file:com.netscape.ca.CertificateAuthority.java
/** * Create a new lightweight authority signed by this authority. * * This method DOES NOT add the new CA to caMap; it is the * caller's responsibility./*from w ww. j ava2 s . c o m*/ */ public ICertificateAuthority createSubCA(IAuthToken authToken, String subjectDN, String description) throws EBaseException { ensureReady(); // check requested DN X500Name subjectX500Name = null; try { subjectX500Name = new X500Name(subjectDN); } catch (IOException e) { throw new IllegalArgumentException("Invalid Subject DN: " + subjectDN); } ensureAuthorityDNAvailable(subjectX500Name); // generate authority ID and nickname AuthorityID aid = new AuthorityID(); String aidString = aid.toString(); String nickname = hostCA.getNickname() + " " + aidString; // build database entry String dn = "cn=" + aidString + "," + authorityBaseDN(); logger.debug("createSubCA: DN = " + dn); String parentDNString = null; try { parentDNString = mName.toLdapDNString(); } catch (IOException e) { throw new EBaseException("Failed to convert issuer DN to string: " + e); } String thisClone = CMS.getEEHost() + ":" + CMS.getEESSLPort(); LDAPAttribute[] attrs = { new LDAPAttribute("objectclass", "authority"), new LDAPAttribute("cn", aidString), new LDAPAttribute("authorityID", aidString), new LDAPAttribute("authorityKeyNickname", nickname), new LDAPAttribute("authorityKeyHost", thisClone), new LDAPAttribute("authorityEnabled", "TRUE"), new LDAPAttribute("authorityDN", subjectDN), new LDAPAttribute("authorityParentDN", parentDNString) }; LDAPAttributeSet attrSet = new LDAPAttributeSet(attrs); if (this.authorityID != null) attrSet.add(new LDAPAttribute("authorityParentID", this.authorityID.toString())); if (description != null) attrSet.add(new LDAPAttribute("description", description)); LDAPEntry ldapEntry = new LDAPEntry(dn, attrSet); addAuthorityEntry(aid, ldapEntry); X509CertImpl cert = null; try { // Generate signing key CryptoManager cryptoManager = CryptoManager.getInstance(); // TODO read PROP_TOKEN_NAME config CryptoToken token = cryptoManager.getInternalKeyStorageToken(); // TODO algorithm parameter KeyPairGenerator gen = token.getKeyPairGenerator(KeyPairAlgorithm.RSA); gen.initialize(2048); KeyPair keypair = gen.genKeyPair(); PublicKey pub = keypair.getPublic(); X509Key x509key = CryptoUtil.convertPublicKeyToX509Key(pub); // Create pkcs10 request logger.debug("createSubCA: creating pkcs10 request"); PKCS10 pkcs10 = new PKCS10(x509key); Signature signature = Signature.getInstance("SHA256withRSA"); signature.initSign(keypair.getPrivate()); pkcs10.encodeAndSign(new X500Signer(signature, subjectX500Name)); ByteArrayOutputStream out = new ByteArrayOutputStream(); pkcs10.print(new PrintStream(out)); String pkcs10String = out.toString(); // Sign certificate Locale locale = Locale.getDefault(); String profileId = "caCACert"; IProfileSubsystem ps = (IProfileSubsystem) CMS.getSubsystem(IProfileSubsystem.ID); IProfile profile = ps.getProfile(profileId); ArgBlock argBlock = new ArgBlock(); argBlock.set("cert_request_type", "pkcs10"); argBlock.set("cert_request", pkcs10String); CertEnrollmentRequest certRequest = CertEnrollmentRequestFactory.create(argBlock, profile, locale); EnrollmentProcessor processor = new EnrollmentProcessor("createSubCA", locale); Map<String, Object> resultMap = processor.processEnrollment(certRequest, null, authorityID, null, authToken); IRequest requests[] = (IRequest[]) resultMap.get(CAProcessor.ARG_REQUESTS); IRequest request = requests[0]; Integer result = request.getExtDataInInteger(IRequest.RESULT); if (result != null && !result.equals(IRequest.RES_SUCCESS)) throw new EBaseException( "createSubCA: certificate request submission resulted in error: " + result); RequestStatus requestStatus = request.getRequestStatus(); if (requestStatus != RequestStatus.COMPLETE) { // The request did not complete. Inference: something // incorrect in the request (e.g. profile constraint // violated). String msg = "Failed to issue CA certificate. Final status: " + requestStatus + "."; String errorMsg = request.getExtDataInString(IRequest.ERROR); if (errorMsg != null) msg += " Additional info: " + errorMsg; throw new BadRequestDataException(msg); } // Add certificate to nssdb cert = request.getExtDataInCert(IEnrollProfile.REQUEST_ISSUED_CERT); cryptoManager.importCertPackage(cert.getEncoded(), nickname); } catch (Exception e) { // something went wrong; delete just-added entry logger.error("Error creating lightweight CA certificate: " + e.getMessage(), e); try { deleteAuthorityEntry(aid); } catch (ELdapException e2) { // we are about to throw ECAException, so just // log this error. logger.error("Error deleting new authority entry after failure during certificate generation: " + e2.getMessage(), e2); } if (e instanceof BadRequestDataException) throw (BadRequestDataException) e; // re-throw else throw new ECAException("Error creating lightweight CA certificate: " + e, e); } CertificateAuthority ca = new CertificateAuthority(hostCA, subjectX500Name, aid, this.authorityID, cert.getSerialNumber(), nickname, Collections.singleton(thisClone), description, true); // Update authority record with serial of issued cert LDAPModificationSet mods = new LDAPModificationSet(); mods.add(LDAPModification.REPLACE, new LDAPAttribute("authoritySerial", cert.getSerialNumber().toString())); ca.modifyAuthorityEntry(mods); return ca; }