List of usage examples for java.security Signature update
public final void update(ByteBuffer data) throws SignatureException
From source file:es.gob.afirma.signers.ooxml.be.fedict.eid.applet.service.signer.AbstractXmlSignatureService.java
@SuppressWarnings("unchecked") private byte[] getSignedXML(final String digestAlgo, final List<DigestInfo> digestInfos, final List<X509Certificate> signingCertificateChain, final PrivateKey signingKey) throws ParserConfigurationException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException, javax.xml.crypto.dsig.XMLSignatureException, TransformerException, IOException, SAXException {/*from ww w . j a va 2 s . c o m*/ // DOM Document construction. Document document = getEnvelopingDocument(); if (null == document) { final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); document = documentBuilderFactory.newDocumentBuilder().newDocument(); } final XMLSignContext xmlSignContext = new DOMSignContext(signingKey, document); final URIDereferencer uriDereferencer = getURIDereferencer(); if (null != uriDereferencer) { xmlSignContext.setURIDereferencer(uriDereferencer); } final XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM", //$NON-NLS-1$ new org.jcp.xml.dsig.internal.dom.XMLDSigRI()); // Add ds:References that come from signing client local files. final List<Reference> references = new LinkedList<Reference>(); addDigestInfosAsReferences(digestInfos, signatureFactory, references); // Invoke the signature facets. final String signatureId = "xmldsig-" + UUID.randomUUID().toString(); //$NON-NLS-1$ final List<XMLObject> objects = new LinkedList<XMLObject>(); for (final SignatureFacet signatureFacet : this.signatureFacets) { signatureFacet.preSign(signatureFactory, document, signatureId, signingCertificateChain, references, objects); } // ds:SignedInfo final SignatureMethod signatureMethod = signatureFactory.newSignatureMethod(getSignatureMethod(digestAlgo), null); final SignedInfo signedInfo = signatureFactory.newSignedInfo(signatureFactory.newCanonicalizationMethod( getCanonicalizationMethod(), (C14NMethodParameterSpec) null), signatureMethod, references); // Creamos el KeyInfo final KeyInfoFactory kif = signatureFactory.getKeyInfoFactory(); final List<Object> x509Content = new ArrayList<Object>(); x509Content.add(signingCertificateChain.get(0)); final List<Object> content = new ArrayList<Object>(); try { content.add(kif.newKeyValue(signingCertificateChain.get(0).getPublicKey())); } catch (final Exception e) { Logger.getLogger("es.gob.afirma") //$NON-NLS-1$ .severe("Error creando el KeyInfo, la informacion puede resultar incompleta: " + e); //$NON-NLS-1$ } content.add(kif.newX509Data(x509Content)); // JSR105 ds:Signature creation final String signatureValueId = signatureId + "-signature-value"; //$NON-NLS-1$ final javax.xml.crypto.dsig.XMLSignature xmlSignature = signatureFactory.newXMLSignature(signedInfo, kif.newKeyInfo(content), // KeyInfo objects, signatureId, signatureValueId); // ds:Signature Marshalling. final DOMXMLSignature domXmlSignature = (DOMXMLSignature) xmlSignature; Node documentNode = document.getDocumentElement(); if (null == documentNode) { documentNode = document; // In case of an empty DOM document. } final String dsPrefix = null; domXmlSignature.marshal(documentNode, dsPrefix, (DOMCryptoContext) xmlSignContext); // Completion of undigested ds:References in the ds:Manifests. for (final XMLObject object : objects) { final List<XMLStructure> objectContentList = object.getContent(); for (final XMLStructure objectContent : objectContentList) { if (!(objectContent instanceof Manifest)) { continue; } final Manifest manifest = (Manifest) objectContent; final List<Reference> manifestReferences = manifest.getReferences(); for (final Reference manifestReference : manifestReferences) { if (null != manifestReference.getDigestValue()) { continue; } final DOMReference manifestDOMReference = (DOMReference) manifestReference; manifestDOMReference.digest(xmlSignContext); } } } // Completion of undigested ds:References. final List<Reference> signedInfoReferences = signedInfo.getReferences(); for (final Reference signedInfoReference : signedInfoReferences) { final DOMReference domReference = (DOMReference) signedInfoReference; if (null != domReference.getDigestValue()) { // ds:Reference with external digest value continue; } domReference.digest(xmlSignContext); } // Calculation of signature final DOMSignedInfo domSignedInfo = (DOMSignedInfo) signedInfo; final ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); domSignedInfo.canonicalize(xmlSignContext, dataStream); final byte[] octets = dataStream.toByteArray(); final Signature sig = Signature.getInstance(digestAlgo.replace("-", "") + "withRSA"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ final byte[] sigBytes; try { sig.initSign(signingKey); sig.update(octets); sigBytes = sig.sign(); } catch (final Exception e) { throw new javax.xml.crypto.dsig.XMLSignatureException( "Error en la firma PKCS#1 ('" + digestAlgo + "withRSA): " + e); //$NON-NLS-1$ //$NON-NLS-2$ } // Sacamos el pre-XML a un OutputStream final ByteArrayOutputStream baos = new ByteArrayOutputStream(); writeDocument(document, baos); // Ya tenemos el XML, con la firma vacia y el SignatureValue, cada uno // por su lado... return postSign(baos.toByteArray(), signingCertificateChain, signatureId, sigBytes); }
From source file:be.e_contract.eid.applet.service.impl.handler.SignatureDataMessageHandler.java
@Override public Object handleMessage(SignatureDataMessage message, Map<String, String> httpHeaders, HttpServletRequest request, HttpSession session) throws ServletException { byte[] signatureValue = message.signatureValue; List<X509Certificate> certificateChain = message.certificateChain; if (certificateChain.isEmpty()) { throw new ServletException("certificate chain is empty"); }/*from www.j a v a 2s. co m*/ X509Certificate signingCertificate = certificateChain.get(0); if (null == signingCertificate) { throw new ServletException("non-repudiation certificate missing"); } LOG.debug("non-repudiation signing certificate: " + signingCertificate.getSubjectX500Principal()); PublicKey signingPublicKey = signingCertificate.getPublicKey(); BeIDContextQualifier contextQualifier = new BeIDContextQualifier(request); /* * Verify the signature. */ String digestAlgo = this.signatureState.getDigestAlgo(); byte[] expectedDigestValue = this.signatureState.getDigestValue(); if (digestAlgo.endsWith("-PSS")) { LOG.debug("verifying RSA/PSS signature"); try { Signature signature = Signature.getInstance("RAWRSASSA-PSS", BouncyCastleProvider.PROVIDER_NAME); if ("SHA-256-PSS".equals(digestAlgo)) { LOG.debug("RSA/PSS SHA256"); signature.setParameter( new PSSParameterSpec("SHA-256", "MGF1", new MGF1ParameterSpec("SHA-256"), 32, 1)); } signature.initVerify(signingPublicKey); signature.update(expectedDigestValue); boolean result = signature.verify(signatureValue); if (false == result) { SecurityAuditEvent securityAuditEvent = new SecurityAuditEvent(Incident.SIGNATURE, signingCertificate, signatureValue); this.securityAuditEvent.select(contextQualifier).fire(securityAuditEvent); throw new SecurityException("signature incorrect"); } } catch (Exception e) { LOG.debug("signature verification error: " + e.getMessage(), e); SecurityAuditEvent securityAuditEvent = new SecurityAuditEvent(Incident.SIGNATURE, signingCertificate, signatureValue); this.securityAuditEvent.select(contextQualifier).fire(securityAuditEvent); throw new ServletException("signature verification error: " + e.getMessage(), e); } } else { try { Signature signature = Signature.getInstance("RawRSA", BouncyCastleProvider.PROVIDER_NAME); signature.initVerify(signingPublicKey); ByteArrayOutputStream digestInfo = new ByteArrayOutputStream(); if ("SHA-1".equals(digestAlgo) || "SHA1".equals(digestAlgo)) { digestInfo.write(SHA1_DIGEST_INFO_PREFIX); } else if ("SHA-224".equals(digestAlgo)) { digestInfo.write(SHA224_DIGEST_INFO_PREFIX); } else if ("SHA-256".equals(digestAlgo)) { digestInfo.write(SHA256_DIGEST_INFO_PREFIX); } else if ("SHA-384".equals(digestAlgo)) { digestInfo.write(SHA384_DIGEST_INFO_PREFIX); } else if ("SHA-512".equals(digestAlgo)) { digestInfo.write(SHA512_DIGEST_INFO_PREFIX); } else if ("RIPEMD160".equals(digestAlgo)) { digestInfo.write(RIPEMD160_DIGEST_INFO_PREFIX); } else if ("RIPEMD128".equals(digestAlgo)) { digestInfo.write(RIPEMD128_DIGEST_INFO_PREFIX); } else if ("RIPEMD256".equals(digestAlgo)) { digestInfo.write(RIPEMD256_DIGEST_INFO_PREFIX); } digestInfo.write(expectedDigestValue); signature.update(digestInfo.toByteArray()); boolean result = signature.verify(signatureValue); if (false == result) { SecurityAuditEvent securityAuditEvent = new SecurityAuditEvent(Incident.SIGNATURE, signingCertificate, signatureValue); this.securityAuditEvent.select(contextQualifier).fire(securityAuditEvent); throw new SecurityException("signature incorrect"); } } catch (Exception e) { LOG.debug("signature verification error: " + e.getMessage()); SecurityAuditEvent securityAuditEvent = new SecurityAuditEvent(Incident.SIGNATURE, signingCertificate, signatureValue); this.securityAuditEvent.select(contextQualifier).fire(securityAuditEvent); throw new ServletException("signature verification error: " + e.getMessage(), e); } } SignatureEvent signatureEvent = new SignatureEvent(signatureValue, certificateChain); try { this.signatureEvent.select(contextQualifier).fire(signatureEvent); } catch (ExpiredCertificateSecurityException e) { return new FinishedMessage(ErrorCode.CERTIFICATE_EXPIRED); } catch (RevokedCertificateSecurityException e) { return new FinishedMessage(ErrorCode.CERTIFICATE_REVOKED); } catch (TrustCertificateSecurityException e) { return new FinishedMessage(ErrorCode.CERTIFICATE_NOT_TRUSTED); } catch (CertificateSecurityException e) { return new FinishedMessage(ErrorCode.CERTIFICATE); } if (null != signatureEvent.getError()) { SecurityAuditEvent securityAuditEvent = new SecurityAuditEvent(Incident.TRUST, signingCertificate); this.securityAuditEvent.select(contextQualifier).fire(securityAuditEvent); return new FinishedMessage(signatureEvent.getError()); } return new FinishedMessage(); }
From source file:org.orbeon.oxf.processor.SignatureVerifierProcessor.java
public ProcessorOutput createOutput(String name) { final ProcessorOutput output = new ProcessorOutputImpl(SignatureVerifierProcessor.this, name) { public void readImpl(PipelineContext context, final XMLReceiver xmlReceiver) { try { final Document pubDoc = readCacheInputAsDOM4J(context, INPUT_PUBLIC_KEY); final String pubString = XPathUtils.selectStringValueNormalize(pubDoc, "/public-key"); final byte[] pubBytes = Base64.decode(pubString); final X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(pubBytes); final KeyFactory keyFactory = KeyFactory.getInstance("DSA"); final PublicKey pubKey = keyFactory.generatePublic(pubKeySpec); final Signature dsa = Signature.getInstance("SHA1withDSA"); dsa.initVerify(pubKey);/*from www . j a v a 2 s . co m*/ final Document data = readInputAsDOM4J(context, INPUT_DATA); final Node sigDataNode = data.selectSingleNode("/signed-data/data/*"); final String sig = StringUtils .trimToEmpty(XPathUtils.selectStringValue(data, "/signed-data/signature")); sigDataNode.detach(); final Document sigData = new NonLazyUserDataDocument(); sigData.add(sigDataNode); dsa.update(Dom4jUtils.domToString(sigData).getBytes("utf-8")); // Verify signature and throw in case of failure try { if (!dsa.verify(Base64.decode(sig))) throw new OXFException("Signature verification failed"); } catch (SignatureException e) { throw e; } catch (Exception e) { // A number of things can fail above, including Base64 decoding // NOTE: We don't pas the cause so that we can match on SignatureException as root Exception throw new SignatureException("Signature verification failed"); } // Signature verification passed final LocationSAXWriter saw = new LocationSAXWriter(); saw.setContentHandler(xmlReceiver); saw.write(sigData); } catch (Exception e) { throw new OXFException(e); } } }; addOutput(name, output); return output; }
From source file:org.loklak.api.cms.LoginService.java
@Override public JSONObject serviceImpl(Query post, HttpServletResponse response, Authorization authorization, final JSONObjectWithDefault permissions) throws APIException { // login check for app if (post.get("checkLogin", false)) { JSONObject result = new JSONObject(); if (authorization.getIdentity().isEmail()) { result.put("loggedIn", true); result.put("message", "You are logged in as " + authorization.getIdentity().getName()); } else {/*from w ww .j av a 2s. c om*/ result.put("loggedIn", false); result.put("message", "Not logged in"); } return result; } // do logout if requested if (post.get("logout", false)) { // logout if requested // invalidate session post.getRequest().getSession().invalidate(); // delete cookie if set deleteLoginCookie(response); JSONObject result = new JSONObject(); result.put("message", "Logout successful"); return result; } // check login type by checking which parameters are set boolean passwordLogin = false; boolean pubkeyHello = false; boolean pubkeyLogin = false; if (post.get("login", null) != null && post.get("password", null) != null && post.get("type", null) != null) { passwordLogin = true; } else if (post.get("login", null) != null && post.get("keyhash", null) != null) { pubkeyHello = true; } else if (post.get("sessionID", null) != null && post.get("response", null) != null) { pubkeyLogin = true; } else { throw new APIException(400, "Bad login parameters."); } // check if user is blocked because of too many invalid login attempts checkInvalidLogins(post, authorization, permissions); if (passwordLogin) { // do login via password String login = post.get("login", null); String password = post.get("password", null); String type = post.get("type", null); Authentication authentication = getAuthentication(post, authorization, new ClientCredential(ClientCredential.Type.passwd_login, login)); ClientIdentity identity = authentication.getIdentity(); // check if the password is valid String passwordHash; String salt; try { passwordHash = authentication.getString("passwordHash"); salt = authentication.getString("salt"); } catch (Throwable e) { Log.getLog().info("Invalid login try for user: " + identity.getName() + " from host: " + post.getClientHost() + " : password or salt missing in database"); throw new APIException(422, "Invalid credentials"); } if (!passwordHash.equals(getHash(password, salt))) { // save invalid login in accounting object authorization.getAccounting().addRequest(this.getClass().getCanonicalName(), "invalid login"); Log.getLog().info("Invalid login try for user: " + identity.getName() + " via passwd from host: " + post.getClientHost()); throw new APIException(422, "Invalid credentials"); } JSONObject result = new JSONObject(); switch (type) { case "session": // create a browser session post.getRequest().getSession().setAttribute("identity", identity); break; case "cookie": // set a long living cookie // create random string as token String loginToken = createRandomString(30); // create cookie Cookie loginCookie = new Cookie("login", loginToken); loginCookie.setPath("/"); loginCookie.setMaxAge(defaultCookieTime.intValue()); // write cookie to database ClientCredential cookieCredential = new ClientCredential(ClientCredential.Type.cookie, loginToken); JSONObject user_obj = new JSONObject(); user_obj.put("id", identity.toString()); user_obj.put("expires_on", Instant.now().getEpochSecond() + defaultCookieTime); DAO.authentication.put(cookieCredential.toString(), user_obj, cookieCredential.isPersistent()); response.addCookie(loginCookie); break; case "access-token": // create and display an access token long valid_seconds; try { valid_seconds = post.get("valid_seconds", defaultAccessTokenExpireTime); } catch (Throwable e) { throw new APIException(400, "Invalid value for 'valid_seconds'"); } String token = createAccessToken(identity, valid_seconds); if (valid_seconds == -1) result.put("valid_seconds", "forever"); else result.put("valid_seconds", valid_seconds); result.put("access_token", token); break; default: throw new APIException(400, "Invalid type"); } Log.getLog().info( "login for user: " + identity.getName() + " via passwd from host: " + post.getClientHost()); result.put("message", "You are logged in as " + identity.getName()); return result; } else if (pubkeyHello) { // first part of pubkey login: if the key hash is known, create a challenge String login = post.get("login", null); String keyHash = post.get("keyhash", null); Authentication authentication = getAuthentication(post, authorization, new ClientCredential(ClientCredential.Type.passwd_login, login)); ClientIdentity identity = authentication.getIdentity(); if (!DAO.login_keys.has(identity.toString()) || !DAO.login_keys.getJSONObject(identity.toString()).has(keyHash)) throw new APIException(400, "Unknown key"); String challengeString = createRandomString(30); String newSessionID = createRandomString(30); ClientCredential credential = new ClientCredential(ClientCredential.Type.pubkey_challange, newSessionID); Authentication challenge_auth = new Authentication(credential, DAO.authentication); challenge_auth.setIdentity(identity); challenge_auth.put("activated", true); challenge_auth.put("challenge", challengeString); challenge_auth.put("key", DAO.login_keys.getJSONObject(identity.toString()).getString(keyHash)); challenge_auth.setExpireTime(60 * 10); JSONObject result = new JSONObject(); result.put("challenge", challengeString); result.put("sessionID", newSessionID); result.put("message", "Found valid key for this user. Sign the challenge with you public key and send it back, together with the sessionID"); return result; } else if (pubkeyLogin) { // second part of pubkey login: verify if the response to the challange is valid String sessionID = post.get("sessionID", null); String challangeResponse = post.get("response", null); Authentication authentication = getAuthentication(post, authorization, new ClientCredential(ClientCredential.Type.pubkey_challange, sessionID)); ClientIdentity identity = authentication.getIdentity(); String challenge = authentication.getString("challenge"); PublicKey key = IO.decodePublicKey(authentication.getString("key"), "RSA"); Signature sig; boolean verified; try { sig = Signature.getInstance("SHA256withRSA"); sig.initVerify(key); sig.update(challenge.getBytes()); verified = sig.verify(Base64.getDecoder().decode(challangeResponse)); } catch (NoSuchAlgorithmException e) { throw new APIException(400, "No such algorithm"); } catch (InvalidKeyException e) { throw new APIException(400, "Invalid key"); } catch (Throwable e) { throw new APIException(400, "Bad signature"); } if (verified) { long valid_seconds; try { valid_seconds = post.get("valid_seconds", defaultAccessTokenExpireTime); } catch (Throwable e) { throw new APIException(400, "Invalid value for 'valid_seconds'"); } String token = createAccessToken(identity, valid_seconds); JSONObject result = new JSONObject(); if (valid_seconds == -1) result.put("valid_seconds", "forever"); else result.put("valid_seconds", valid_seconds); result.put("access_token", token); return result; } else { authorization.getAccounting().addRequest(this.getClass().getCanonicalName(), "invalid login"); throw new APIException(400, "Bad Signature"); } } throw new APIException(500, "Server error"); }
From source file:org.loklak.api.aaa.LoginService.java
@Override public JSONObject serviceImpl(Query post, HttpServletResponse response, Authorization authorization, final JSONObjectWithDefault permissions) throws APIException { // login check for app if (post.get("checkLogin", false)) { JSONObject result = new JSONObject(); if (authorization.getIdentity().isEmail()) { result.put("loggedIn", true); result.put("message", "You are logged in as " + authorization.getIdentity().getName()); } else {/* w w w .j a v a2 s.c om*/ result.put("loggedIn", false); result.put("message", "Not logged in"); } return result; } // do logout if requested boolean logout = post.get("logout", false); boolean delete = post.get("delete", false); if (logout || delete) { // logout if requested // invalidate session post.getRequest().getSession().invalidate(); // delete cookie if set deleteLoginCookie(response); if (delete) { ClientCredential pwcredential = new ClientCredential(authorization.getIdentity()); delete = DAO.authentication.has(pwcredential.toString()); if (delete) DAO.authentication.remove(pwcredential.toString()); } JSONObject result = new JSONObject(); result.put("message", delete ? "Account deletion successful" : "Logout successful"); return result; } // check login type by checking which parameters are set boolean passwordLogin = false; boolean pubkeyHello = false; boolean pubkeyLogin = false; if (post.get("login", null) != null && post.get("password", null) != null && post.get("type", null) != null) { passwordLogin = true; } else if (post.get("login", null) != null && post.get("keyhash", null) != null) { pubkeyHello = true; } else if (post.get("sessionID", null) != null && post.get("response", null) != null) { pubkeyLogin = true; } else { throw new APIException(400, "Bad login parameters."); } // check if user is blocked because of too many invalid login attempts checkInvalidLogins(post, authorization, permissions); if (passwordLogin) { // do login via password String login = post.get("login", null); String password = post.get("password", null); String type = post.get("type", null); ClientCredential pwcredential = new ClientCredential(ClientCredential.Type.passwd_login, login); Authentication authentication = getAuthentication(post, authorization, pwcredential); ClientIdentity identity = authentication.getIdentity(); // check if the password is valid String passwordHash; String salt; try { passwordHash = authentication.getString("passwordHash"); salt = authentication.getString("salt"); } catch (Throwable e) { Log.getLog().info("Invalid login try for user: " + identity.getName() + " from host: " + post.getClientHost() + " : password or salt missing in database"); throw new APIException(422, "Invalid credentials"); } if (!passwordHash.equals(getHash(password, salt))) { // save invalid login in accounting object authorization.getAccounting().addRequest(this.getClass().getCanonicalName(), "invalid login"); Log.getLog().info("Invalid login try for user: " + identity.getName() + " via passwd from host: " + post.getClientHost()); throw new APIException(422, "Invalid credentials"); } JSONObject result = new JSONObject(); switch (type) { case "session": // create a browser session post.getRequest().getSession().setAttribute("identity", identity); break; case "cookie": // set a long living cookie // create random string as token String loginToken = createRandomString(30); // create cookie Cookie loginCookie = new Cookie("login", loginToken); loginCookie.setPath("/"); loginCookie.setMaxAge(defaultCookieTime.intValue()); // write cookie to database ClientCredential cookieCredential = new ClientCredential(ClientCredential.Type.cookie, loginToken); JSONObject user_obj = new JSONObject(); user_obj.put("id", identity.toString()); user_obj.put("expires_on", Instant.now().getEpochSecond() + defaultCookieTime); DAO.authentication.put(cookieCredential.toString(), user_obj, cookieCredential.isPersistent()); response.addCookie(loginCookie); break; case "access-token": // create and display an access token long valid_seconds; try { valid_seconds = post.get("valid_seconds", defaultAccessTokenExpireTime); } catch (Throwable e) { throw new APIException(400, "Invalid value for 'valid_seconds'"); } String token = createAccessToken(identity, valid_seconds); if (valid_seconds == -1) result.put("valid_seconds", "forever"); else result.put("valid_seconds", valid_seconds); result.put("access_token", token); break; default: throw new APIException(400, "Invalid type"); } Log.getLog().info( "login for user: " + identity.getName() + " via passwd from host: " + post.getClientHost()); result.put("message", "You are logged in as " + identity.getName()); return result; } else if (pubkeyHello) { // first part of pubkey login: if the key hash is known, create a challenge String login = post.get("login", null); String keyHash = post.get("keyhash", null); Authentication authentication = getAuthentication(post, authorization, new ClientCredential(ClientCredential.Type.passwd_login, login)); ClientIdentity identity = authentication.getIdentity(); if (!DAO.login_keys.has(identity.toString()) || !DAO.login_keys.getJSONObject(identity.toString()).has(keyHash)) throw new APIException(400, "Unknown key"); String challengeString = createRandomString(30); String newSessionID = createRandomString(30); ClientCredential credential = new ClientCredential(ClientCredential.Type.pubkey_challange, newSessionID); Authentication challenge_auth = new Authentication(credential, DAO.authentication); challenge_auth.setIdentity(identity); challenge_auth.put("activated", true); challenge_auth.put("challenge", challengeString); challenge_auth.put("key", DAO.login_keys.getJSONObject(identity.toString()).getString(keyHash)); challenge_auth.setExpireTime(60 * 10); JSONObject result = new JSONObject(); result.put("challenge", challengeString); result.put("sessionID", newSessionID); result.put("message", "Found valid key for this user. Sign the challenge with you public key and send it back, together with the sessionID"); return result; } else if (pubkeyLogin) { // second part of pubkey login: verify if the response to the challange is valid String sessionID = post.get("sessionID", null); String challangeResponse = post.get("response", null); Authentication authentication = getAuthentication(post, authorization, new ClientCredential(ClientCredential.Type.pubkey_challange, sessionID)); ClientIdentity identity = authentication.getIdentity(); String challenge = authentication.getString("challenge"); PublicKey key = IO.decodePublicKey(authentication.getString("key"), "RSA"); Signature sig; boolean verified; try { sig = Signature.getInstance("SHA256withRSA"); sig.initVerify(key); sig.update(challenge.getBytes()); verified = sig.verify(Base64.getDecoder().decode(challangeResponse)); } catch (NoSuchAlgorithmException e) { throw new APIException(400, "No such algorithm"); } catch (InvalidKeyException e) { throw new APIException(400, "Invalid key"); } catch (Throwable e) { throw new APIException(400, "Bad signature"); } if (verified) { long valid_seconds; try { valid_seconds = post.get("valid_seconds", defaultAccessTokenExpireTime); } catch (Throwable e) { throw new APIException(400, "Invalid value for 'valid_seconds'"); } String token = createAccessToken(identity, valid_seconds); JSONObject result = new JSONObject(); if (valid_seconds == -1) result.put("valid_seconds", "forever"); else result.put("valid_seconds", valid_seconds); result.put("access_token", token); return result; } else { authorization.getAccounting().addRequest(this.getClass().getCanonicalName(), "invalid login"); throw new APIException(400, "Bad Signature"); } } throw new APIException(500, "Server error"); }
From source file:ai.susi.server.api.aaa.LoginService.java
@Override public JSONObject serviceImpl(Query post, HttpServletResponse response, Authorization authorization, final JsonObjectWithDefault permissions) throws APIException { // login check for app if (post.get("checkLogin", false)) { JSONObject result = new JSONObject(); if (authorization.getIdentity().isEmail()) { result.put("loggedIn", true); result.put("message", "You are logged in as " + authorization.getIdentity().getName()); } else {/* w w w . ja v a 2 s . c o m*/ result.put("loggedIn", false); result.put("message", "Not logged in"); } return result; } // do logout if requested boolean logout = post.get("logout", false); boolean delete = post.get("delete", false); if (logout || delete) { // logout if requested // invalidate session post.getRequest().getSession().invalidate(); // delete cookie if set deleteLoginCookie(response); if (delete) { ClientCredential pwcredential = new ClientCredential(authorization.getIdentity()); delete = DAO.authentication.has(pwcredential.toString()); if (delete) DAO.authentication.remove(pwcredential.toString()); } JSONObject result = new JSONObject(); result.put("message", delete ? "Account deletion successful" : "Logout successful"); return result; } // check login type by checking which parameters are set boolean passwordLogin = false; boolean pubkeyHello = false; boolean pubkeyLogin = false; if (post.get("login", null) != null && post.get("password", null) != null && post.get("type", null) != null) { passwordLogin = true; } else if (post.get("login", null) != null && post.get("keyhash", null) != null) { pubkeyHello = true; } else if (post.get("sessionID", null) != null && post.get("response", null) != null) { pubkeyLogin = true; } else { throw new APIException(400, "Bad login parameters."); } // check if user is blocked because of too many invalid login attempts checkInvalidLogins(post, authorization, permissions); if (passwordLogin) { // do login via password String login = post.get("login", null); String password = post.get("password", null); String type = post.get("type", null); ClientCredential pwcredential = new ClientCredential(ClientCredential.Type.passwd_login, login); Authentication authentication = getAuthentication(post, authorization, pwcredential); ClientIdentity identity = authentication.getIdentity(); // check if the password is valid String passwordHash; String salt; try { passwordHash = authentication.getString("passwordHash"); salt = authentication.getString("salt"); } catch (Throwable e) { Log.getLog().info("Invalid login try for user: " + identity.getName() + " from host: " + post.getClientHost() + " : password or salt missing in database"); throw new APIException(422, "Invalid credentials"); } if (!passwordHash.equals(getHash(password, salt))) { // save invalid login in accounting object authorization.getAccounting().addRequest(this.getClass().getCanonicalName(), "invalid login"); Log.getLog().info("Invalid login try for user: " + identity.getName() + " via passwd from host: " + post.getClientHost()); throw new APIException(422, "Invalid credentials"); } JSONObject result = new JSONObject(); switch (type) { case "session": // create a browser session post.getRequest().getSession().setAttribute("identity", identity); break; case "cookie": // set a long living cookie // create random string as token String loginToken = createRandomString(30); // create cookie Cookie loginCookie = new Cookie("login", loginToken); loginCookie.setPath("/"); loginCookie.setMaxAge(defaultCookieTime.intValue()); // write cookie to database ClientCredential cookieCredential = new ClientCredential(ClientCredential.Type.cookie, loginToken); JSONObject user_obj = new JSONObject(); user_obj.put("id", identity.toString()); user_obj.put("expires_on", Instant.now().getEpochSecond() + defaultCookieTime); DAO.authentication.put(cookieCredential.toString(), user_obj, cookieCredential.isPersistent()); response.addCookie(loginCookie); break; case "access-token": // create and display an access token long valid_seconds; try { valid_seconds = post.get("valid_seconds", defaultAccessTokenExpireTime); } catch (Throwable e) { throw new APIException(400, "Invalid value for 'valid_seconds'"); } String token = createAccessToken(identity, valid_seconds); if (valid_seconds == -1) result.put("valid_seconds", "forever"); else result.put("valid_seconds", valid_seconds); result.put("access_token", token); break; default: throw new APIException(400, "Invalid type"); } Log.getLog().info( "login for user: " + identity.getName() + " via passwd from host: " + post.getClientHost()); result.put("message", "You are logged in as " + identity.getName()); return result; } else if (pubkeyHello) { // first part of pubkey login: if the key hash is known, create a challenge String login = post.get("login", null); String keyHash = post.get("keyhash", null); Authentication authentication = getAuthentication(post, authorization, new ClientCredential(ClientCredential.Type.passwd_login, login)); ClientIdentity identity = authentication.getIdentity(); if (!DAO.login_keys.has(identity.toString()) || !DAO.login_keys.getJSONObject(identity.toString()).has(keyHash)) throw new APIException(400, "Unknown key"); String challengeString = createRandomString(30); String newSessionID = createRandomString(30); ClientCredential credential = new ClientCredential(ClientCredential.Type.pubkey_challange, newSessionID); Authentication challenge_auth = new Authentication(credential, DAO.authentication); challenge_auth.setIdentity(identity); challenge_auth.put("activated", true); challenge_auth.put("challenge", challengeString); challenge_auth.put("key", DAO.login_keys.getJSONObject(identity.toString()).getString(keyHash)); challenge_auth.setExpireTime(60 * 10); JSONObject result = new JSONObject(); result.put("challenge", challengeString); result.put("sessionID", newSessionID); result.put("message", "Found valid key for this user. Sign the challenge with you public key and send it back, together with the sessionID"); return result; } else if (pubkeyLogin) { // second part of pubkey login: verify if the response to the challange is valid String sessionID = post.get("sessionID", null); String challangeResponse = post.get("response", null); Authentication authentication = getAuthentication(post, authorization, new ClientCredential(ClientCredential.Type.pubkey_challange, sessionID)); ClientIdentity identity = authentication.getIdentity(); String challenge = authentication.getString("challenge"); PublicKey key = IO.decodePublicKey(authentication.getString("key"), "RSA"); Signature sig; boolean verified; try { sig = Signature.getInstance("SHA256withRSA"); sig.initVerify(key); sig.update(challenge.getBytes()); verified = sig.verify(Base64.getDecoder().decode(challangeResponse)); } catch (NoSuchAlgorithmException e) { throw new APIException(400, "No such algorithm"); } catch (InvalidKeyException e) { throw new APIException(400, "Invalid key"); } catch (Throwable e) { throw new APIException(400, "Bad signature"); } if (verified) { long valid_seconds; try { valid_seconds = post.get("valid_seconds", defaultAccessTokenExpireTime); } catch (Throwable e) { throw new APIException(400, "Invalid value for 'valid_seconds'"); } String token = createAccessToken(identity, valid_seconds); JSONObject result = new JSONObject(); if (valid_seconds == -1) result.put("valid_seconds", "forever"); else result.put("valid_seconds", valid_seconds); result.put("access_token", token); return result; } else { authorization.getAccounting().addRequest(this.getClass().getCanonicalName(), "invalid login"); throw new APIException(400, "Bad Signature"); } } throw new APIException(500, "Server error"); }
From source file:org.forgerock.openidm.security.impl.SecurityResourceProvider.java
/** * Verifies that the supplied private key and signed certificate match by signing/verifying some test data. * /*from w w w . ja v a2 s . com*/ * @param privateKey A private key * @param cert the certificate * @throws ResourceException if the verification fails, or an error is encountered. */ protected void verify(PrivateKey privateKey, Certificate cert) throws ResourceException { PublicKey publicKey = cert.getPublicKey(); byte[] data = { 65, 66, 67, 68, 69, 70, 71, 72, 73, 74 }; boolean verified; try { Signature signer = Signature.getInstance(privateKey.getAlgorithm()); signer.initSign(privateKey); signer.update(data); byte[] signed = signer.sign(); Signature verifier = Signature.getInstance(publicKey.getAlgorithm()); verifier.initVerify(publicKey); verifier.update(data); verified = verifier.verify(signed); } catch (Exception e) { throw new InternalServerErrorException("Error verifying private key and signed certificate", e); } if (!verified) { throw new BadRequestException("Private key does not match signed certificate"); } }
From source file:org.apache.cxf.fediz.service.idp.protocols.TrustedIdpSAMLProtocolHandler.java
/** * Sign a request according to the redirect binding spec for Web SSO *///from w w w.j a va2 s . com private void signRequest(String authnRequest, String relayState, Idp config, UriBuilder ub) throws Exception { Crypto crypto = getCrypto(config.getCertificate()); if (crypto == null) { LOG.error("No crypto instance of properties file configured for signature"); throw new IllegalStateException("Invalid IdP configuration"); } String alias = crypto.getDefaultX509Identifier(); X509Certificate cert = CertsUtils.getX509Certificate(crypto, alias); if (cert == null) { LOG.error("No cert was found to sign the request using alias: " + alias); throw new IllegalStateException("Invalid IdP configuration"); } String sigAlgo = SSOConstants.RSA_SHA1; String pubKeyAlgo = cert.getPublicKey().getAlgorithm(); String jceSigAlgo = "SHA1withRSA"; LOG.debug("automatic sig algo detection: " + pubKeyAlgo); if (pubKeyAlgo.equalsIgnoreCase("DSA")) { sigAlgo = SSOConstants.DSA_SHA1; jceSigAlgo = "SHA1withDSA"; } LOG.debug("Using Signature algorithm " + sigAlgo); ub.queryParam(SSOConstants.SIG_ALG, URLEncoder.encode(sigAlgo, "UTF-8")); // Get the password String password = config.getCertificatePassword(); // Get the private key PrivateKey privateKey = crypto.getPrivateKey(alias, password); // Sign the request Signature signature = Signature.getInstance(jceSigAlgo); signature.initSign(privateKey); String requestToSign = SSOConstants.SAML_REQUEST + "=" + authnRequest + "&" + SSOConstants.RELAY_STATE + "=" + relayState + "&" + SSOConstants.SIG_ALG + "=" + URLEncoder.encode(sigAlgo, "UTF-8"); signature.update(requestToSign.getBytes("UTF-8")); byte[] signBytes = signature.sign(); String encodedSignature = Base64.encode(signBytes); ub.queryParam(SSOConstants.SIGNATURE, URLEncoder.encode(encodedSignature, "UTF-8")); }
From source file:test.integ.be.fedict.commons.eid.client.JCATest.java
private void verifySignatureAlgorithm(final String signatureAlgorithm, final PrivateKey privateKey, final PublicKey publicKey) throws Exception { Signature signature = Signature.getInstance(signatureAlgorithm); signature.initSign(privateKey);/*from w w w . j a v a 2 s .com*/ assertTrue(signature.getProvider() instanceof BeIDProvider); final byte[] toBeSigned = "hello world".getBytes(); signature.update(toBeSigned); final byte[] signatureValue = signature.sign(); assertNotNull(signatureValue); signature.initVerify(publicKey); signature.update(toBeSigned); final boolean beIDResult = signature.verify(signatureValue); assertTrue(beIDResult); signature = Signature.getInstance(signatureAlgorithm); signature.initVerify(publicKey); signature.update(toBeSigned); final boolean result = signature.verify(signatureValue); assertTrue(result); RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey; BigInteger signatureValueBigInteger = new BigInteger(signatureValue); BigInteger messageBigInteger = signatureValueBigInteger.modPow(rsaPublicKey.getPublicExponent(), rsaPublicKey.getModulus()); LOG.debug("Padded DigestInfo: " + new String(Hex.encodeHex(messageBigInteger.toByteArray()))); }
From source file:org.wso2.carbon.apimgt.keymgt.token.AbstractJWTGenerator.java
private byte[] signJWT(String assertion, String endUserName) throws APIManagementException { String tenantDomain = null;//from w w w.j a va 2 s . c o m try { //get tenant domain tenantDomain = MultitenantUtils.getTenantDomain(endUserName); //get tenantId int tenantId = APIUtil.getTenantId(endUserName); Key privateKey = null; if (!(privateKeys.containsKey(tenantId))) { APIUtil.loadTenantRegistry(tenantId); //get tenant's key store manager KeyStoreManager tenantKSM = KeyStoreManager.getInstance(tenantId); if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) { //derive key store name String ksName = tenantDomain.trim().replace('.', '-'); String jksName = ksName + ".jks"; //obtain private key //TODO: maintain a hash map with tenants' private keys after first initialization privateKey = tenantKSM.getPrivateKey(jksName, tenantDomain); } else { try { privateKey = tenantKSM.getDefaultPrivateKey(); } catch (Exception e) { log.error("Error while obtaining private key for super tenant", e); } } if (privateKey != null) { privateKeys.put(tenantId, privateKey); } } else { privateKey = privateKeys.get(tenantId); } //initialize signature with private key and algorithm Signature signature = Signature.getInstance(signatureAlgorithm); signature.initSign((PrivateKey) privateKey); //update signature with data to be signed byte[] dataInBytes = assertion.getBytes(Charset.defaultCharset()); signature.update(dataInBytes); //sign the assertion and return the signature return signature.sign(); } catch (NoSuchAlgorithmException e) { String error = "Signature algorithm not found."; //do not log throw new APIManagementException(error, e); } catch (InvalidKeyException e) { String error = "Invalid private key provided for the signature"; //do not log throw new APIManagementException(error, e); } catch (SignatureException e) { String error = "Error in signature"; //do not log throw new APIManagementException(error, e); } catch (RegistryException e) { String error = "Error in loading tenant registry for " + tenantDomain; //do not log throw new APIManagementException(error, e); } }