List of usage examples for java.security Signature getInstance
public static Signature getInstance(String algorithm) throws NoSuchAlgorithmException
From source file:org.wso2.carbon.apimgt.impl.token.AbstractJWTGenerator.java
private byte[] signJWT(String assertion, String endUserName) throws APIManagementException { try {//from ww w. j ava 2s.com //get tenant domain String 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 (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { //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(); signature.update(dataInBytes); //sign the assertion and return the signature byte[] signedInfo = signature.sign(); return signedInfo; } catch (NoSuchAlgorithmException e) { String error = "Signature algorithm not found."; //do not log throw new APIManagementException(error); } catch (InvalidKeyException e) { String error = "Invalid private key provided for the signature"; //do not log throw new APIManagementException(error); } catch (SignatureException e) { String error = "Error in signature"; //do not log throw new APIManagementException(error); } catch (RegistryException e) { throw new APIManagementException("Error occurred while loading tenant registry", e); } }
From source file:org.mitre.openid.connect.client.AbstractOIDCAuthenticationFilter.java
@Override public void afterPropertiesSet() { super.afterPropertiesSet(); Assert.notNull(errorRedirectURI, "An Error Redirect URI must be supplied"); KeyPairGenerator keyPairGenerator; try {/* w w w.ja v a 2 s.c o m*/ keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(KEY_SIZE); KeyPair keyPair = keyPairGenerator.generateKeyPair(); publicKey = keyPair.getPublic(); privateKey = keyPair.getPrivate(); signer = Signature.getInstance(SIGNING_ALGORITHM); } catch (GeneralSecurityException generalSecurityException) { // generalSecurityException.printStackTrace(); throw new IllegalStateException(generalSecurityException); } // prepend the spec necessary SCOPE setScope((scope != null && !scope.isEmpty()) ? SCOPE + " " + scope : SCOPE); }
From source file:be.fedict.eid.applet.service.impl.handler.SignCertificatesDataMessageHandler.java
private void verifySignature(String signatureAlgoName, byte[] signatureData, PublicKey publicKey, HttpServletRequest request, byte[]... data) throws ServletException { Signature signature;/*from w w w . j a v a 2s .c o m*/ try { signature = Signature.getInstance(signatureAlgoName); } catch (NoSuchAlgorithmException e) { throw new ServletException("algo error: " + e.getMessage(), e); } try { signature.initVerify(publicKey); } catch (InvalidKeyException e) { throw new ServletException("key error: " + e.getMessage(), e); } try { for (byte[] dataItem : data) { signature.update(dataItem); } boolean result = signature.verify(signatureData); if (false == result) { AuditService auditService = this.auditServiceLocator.locateService(); if (null != auditService) { String remoteAddress = request.getRemoteAddr(); auditService.identityIntegrityError(remoteAddress); } throw new ServletException("signature incorrect"); } } catch (SignatureException e) { throw new ServletException("signature error: " + e.getMessage(), e); } }
From source file:hudson.cli.CLI.java
/** * @deprecated Specific to {@link Mode#REMOTING}. *///from ww w . jav a 2 s.c o m @Deprecated private Channel connectViaCliPort(URL jenkins, CliPort clip) throws IOException { LOGGER.log(FINE, "Trying to connect directly via Remoting over TCP/IP to {0}", clip.endpoint); if (authorization != null) { LOGGER.warning("-auth ignored when using JNLP agent port"); } final Socket s = new Socket(); // this prevents a connection from silently terminated by the router in between or the other peer // and that goes without unnoticed. However, the time out is often very long (for example 2 hours // by default in Linux) that this alone is enough to prevent that. s.setKeepAlive(true); // we take care of buffering on our own s.setTcpNoDelay(true); OutputStream out; if (httpsProxyTunnel != null) { String[] tokens = httpsProxyTunnel.split(":"); LOGGER.log(Level.FINE, "Using HTTP proxy {0}:{1} to connect to CLI port", new Object[] { tokens[0], tokens[1] }); s.connect(new InetSocketAddress(tokens[0], Integer.parseInt(tokens[1]))); PrintStream o = new PrintStream(s.getOutputStream()); o.print("CONNECT " + clip.endpoint.getHostString() + ":" + clip.endpoint.getPort() + " HTTP/1.0\r\n\r\n"); // read the response from the proxy ByteArrayOutputStream rsp = new ByteArrayOutputStream(); while (!rsp.toString("ISO-8859-1").endsWith("\r\n\r\n")) { int ch = s.getInputStream().read(); if (ch < 0) throw new IOException("Failed to read the HTTP proxy response: " + rsp); rsp.write(ch); } String head = new BufferedReader(new StringReader(rsp.toString("ISO-8859-1"))).readLine(); if (head == null) { throw new IOException("Unexpected empty response"); } if (!(head.startsWith("HTTP/1.0 200 ") || head.startsWith("HTTP/1.1 200 "))) { s.close(); LOGGER.log(Level.SEVERE, "Failed to tunnel the CLI port through the HTTP proxy. Falling back to HTTP."); throw new IOException("Failed to establish a connection through HTTP proxy: " + rsp); } // HTTP proxies (at least the one I tried --- squid) doesn't seem to do half-close very well. // So instead of relying on it, we'll just send the close command and then let the server // cut their side, then close the socket after the join. out = new SocketOutputStream(s) { @Override public void close() throws IOException { // ignore } }; } else { s.connect(clip.endpoint, 3000); out = SocketChannelStream.out(s); } closables.add(new Closeable() { public void close() throws IOException { s.close(); } }); Connection c = new Connection(SocketChannelStream.in(s), out); switch (clip.version) { case 1: DataOutputStream dos = new DataOutputStream(s.getOutputStream()); dos.writeUTF("Protocol:CLI-connect"); // we aren't checking greeting from the server here because I'm too lazy. It gets ignored by Channel constructor. break; case 2: DataInputStream dis = new DataInputStream(s.getInputStream()); dos = new DataOutputStream(s.getOutputStream()); dos.writeUTF("Protocol:CLI2-connect"); String greeting = dis.readUTF(); if (!greeting.equals("Welcome")) throw new IOException("Handshaking failed: " + greeting); try { byte[] secret = c.diffieHellman(false).generateSecret(); SecretKey sessionKey = new SecretKeySpec(Connection.fold(secret, 128 / 8), "AES"); c = c.encryptConnection(sessionKey, "AES/CFB8/NoPadding"); // validate the instance identity, so that we can be sure that we are talking to the same server // and there's no one in the middle. byte[] signature = c.readByteArray(); if (clip.identity != null) { Signature verifier = Signature.getInstance("SHA1withRSA"); verifier.initVerify(clip.getIdentity()); verifier.update(secret); if (!verifier.verify(signature)) throw new IOException("Server identity signature validation failed."); } } catch (GeneralSecurityException e) { throw (IOException) new IOException("Failed to negotiate transport security").initCause(e); } } return new Channel("CLI connection to " + jenkins, pool, new BufferedInputStream(c.in), new BufferedOutputStream(c.out)); }
From source file: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. j ava 2s .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.wso2.carbon.appmgt.gateway.token.AbstractJWTGenerator.java
/** * Helper method to sign the JWT//from www. j a v a2s .co m * * @param assertion Assertion * @param endUserName End user name * @return signed assertion * @throws AppManagementException on error while trying to sign JWT */ private byte[] signJWT(String assertion, String endUserName) throws AppManagementException { int tenantId = getTenantId(endUserName); try { Key privateKey = getPrivateKey(endUserName, tenantId); if (privateKey == null) { throw new AppManagementException("Private key is null for tenant " + 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(StandardCharsets.UTF_8); signature.update(dataInBytes); /* Sign the assertion and return the signature */ byte[] signedInfo = signature.sign(); return signedInfo; } catch (NoSuchAlgorithmException e) { String error = "Signature algorithm " + signatureAlgorithm + " not found."; log.error(error, e); throw new AppManagementException(error, e); } catch (InvalidKeyException e) { String error = "Invalid private key provided for the signature for tenant " + tenantId; log.error(error, e); throw new AppManagementException(error, e); } catch (SignatureException e) { String error = "Error in signature algorithm " + signatureAlgorithm; log.error(error, e); throw new AppManagementException(error, e); } catch (AppManagementException e) { String error = "Error in obtaining tenant's " + tenantId + " private key"; log.error(error, e); throw new AppManagementException(error, e); } }
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 {//from w ww . ja va2 s. com 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:test.integ.be.fedict.commons.eid.client.JCATest.java
@Test public void testNonRepudiationSignature() throws Exception { Security.addProvider(new BeIDProvider()); KeyStore keyStore = KeyStore.getInstance("BeID"); keyStore.load(null);/*from w w w . j a v a2s. co m*/ PrivateKey signPrivateKey = (PrivateKey) keyStore.getKey("Signature", null); Signature signature = Signature.getInstance("SHA1withRSA"); signature.initSign(signPrivateKey); byte[] toBeSigned = "hello world".getBytes(); signature.update(toBeSigned); byte[] signatureValue = signature.sign(); assertNotNull(signatureValue); Certificate[] signCertificateChain = keyStore.getCertificateChain("Signature"); assertNotNull(signCertificateChain); }
From source file:com.kuzumeji.platform.standard.SecurityService.java
/** * ???//from ww w . j a v a 2 s . c o m * <dl> * <dt>? * <dd>SHA-512?RSA??????? * </dl> * @param key ? * @param plain * @return ?? */ public byte[] signature(final PrivateKey key, final byte[] plain) { try { final Signature signatureSign = Signature.getInstance(SIGN_ALGO_NAME); signatureSign.initSign(key, SECURE_RANDOM); signatureSign.update(plain); return signatureSign.sign(); } catch (final NoSuchAlgorithmException | InvalidKeyException | SignatureException e) { throw new RuntimeException(e); } }
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 w w w .j av a 2s . c o 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"); } } }