List of usage examples for java.security Signature getInstance
public static Signature getInstance(String algorithm) throws NoSuchAlgorithmException
From source file:org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.transport.CommunicationUtils.java
/** * Signed a given message using the PrivateKey that's passes in. * * @param message the message to be signed. Ideally some encrypted payload. * @param signatureKey the PrivateKey with which the message is to be signed. * @return the Base64Encoded String of the signed payload. * @throws TransportHandlerException if some error occurs with the signing process which may be related to the * signature algorithm used or the key used for signing. */// ww w .j a v a2s. c o m public static String signMessage(String message, PrivateKey signatureKey) throws TransportHandlerException { Signature signature; String signedEncodedString; try { signature = Signature.getInstance(SIGNATURE_ALG); signature.initSign(signatureKey); signature.update(Base64.decodeBase64(message)); byte[] signatureBytes = signature.sign(); signedEncodedString = Base64.encodeBase64String(signatureBytes); } catch (NoSuchAlgorithmException e) { String errorMsg = "Algorithm not found exception occurred for Signature instance of [" + SIGNATURE_ALG + "]"; log.error(errorMsg); throw new TransportHandlerException(errorMsg, e); } catch (SignatureException e) { String errorMsg = "Signature exception occurred for Signature instance of [" + SIGNATURE_ALG + "]"; log.error(errorMsg); throw new TransportHandlerException(errorMsg, e); } catch (InvalidKeyException e) { String errorMsg = "InvalidKey exception occurred for signatureKey \n[\n" + signatureKey + "\n]\n"; log.error(errorMsg); throw new TransportHandlerException(errorMsg, e); } return signedEncodedString; }
From source file:test.unit.be.fedict.hsm.entity.KeyStoreSingletonBeanTest.java
@Test public void testSignature() throws Exception { EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("test"); EntityManager entityManager = entityManagerFactory.createEntityManager(); EntityTransaction entityTransaction = entityManager.getTransaction(); entityTransaction.begin();/*ww w. j a v a 2 s .c o m*/ KeyStoreEntity keyStoreEntity = new KeyStoreEntity("test", KeyStoreType.PKCS12, KeyStoreSingletonBeanTest.class.getResource("/keystore.p12").toURI().getPath(), "secret"); entityManager.persist(keyStoreEntity); KeyStoreSingletonBean keyStoreSingletonBean = new KeyStoreSingletonBean(); Field entityManagerField = KeyStoreSingletonBean.class.getDeclaredField("entityManager"); entityManagerField.setAccessible(true); entityManagerField.set(keyStoreSingletonBean, entityManager); KeyStoreLoaderBean keyStoreLoaderBean = new KeyStoreLoaderBean(); Field keyStoreLoaderField = KeyStoreSingletonBean.class.getDeclaredField("keyStoreLoader"); keyStoreLoaderField.setAccessible(true); keyStoreLoaderField.set(keyStoreSingletonBean, keyStoreLoaderBean); keyStoreSingletonBean.loadKeys(); keyStoreSingletonBean.newKeyStore(keyStoreEntity.getId()); byte[] toBeSigned = "hello world".getBytes(); MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); messageDigest.update(toBeSigned); byte[] digestValue = messageDigest.digest(); LOG.debug("digest value: " + new String(Hex.encodeHex(digestValue))); byte[] signatureValue = keyStoreSingletonBean.sign(keyStoreEntity.getId(), "alias", "SHA-1", digestValue); assertNotNull(signatureValue); LOG.debug("signature size: " + signatureValue.length); KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load(KeyStoreSingletonBeanTest.class.getResourceAsStream("/keystore.p12"), "secret".toCharArray()); RSAPublicKey publicKey = (RSAPublicKey) keyStore.getCertificate("alias").getPublicKey(); BigInteger signatureValueBigInteger = new BigInteger(signatureValue); BigInteger originalBigInteger = signatureValueBigInteger.modPow(publicKey.getPublicExponent(), publicKey.getModulus()); LOG.debug("original message: " + new String(Hex.encodeHex(originalBigInteger.toByteArray()))); Signature signature = Signature.getInstance("SHA1withRSA"); signature.initVerify(publicKey); signature.update(toBeSigned); boolean result = signature.verify(signatureValue); assertTrue(result); }
From source file:org.apache.abdera2.common.security.HashHelper.java
public static boolean sigval(PublicKey key, String alg, byte[] mat, byte[] dat) { try {/*from w ww . j a v a 2 s .co m*/ Signature sig = Signature.getInstance(alg); sig.initVerify(key); sig.update(mat); return sig.verify(dat); } catch (Throwable t) { throw ExceptionHelper.propogate(t); } }
From source file:org.wso2.carbon.device.mgt.iot.agent.firealarm.transport.CommunicationUtils.java
/** * Signed a given message using the PrivateKey that's passes in. * * @param message the message to be signed. Ideally some encrypted payload. * @param signatureKey the PrivateKey with which the message is to be signed. * @return the Base64Encoded String of the signed payload. * @throws AgentCoreOperationException if some error occurs with the signing process which may be related to the * signature algorithm used or the key used for signing. *///from ww w . j av a2 s . c o m public static String signMessage(String message, PrivateKey signatureKey) throws AgentCoreOperationException { Signature signature; String signedEncodedString; try { signature = Signature.getInstance(SIGNATURE_ALG); signature.initSign(signatureKey); signature.update(Base64.decodeBase64(message)); byte[] signatureBytes = signature.sign(); signedEncodedString = Base64.encodeBase64String(signatureBytes); } catch (NoSuchAlgorithmException e) { String errorMsg = "Algorithm not found exception occurred for Signature instance of [" + SIGNATURE_ALG + "]"; log.error(errorMsg); throw new AgentCoreOperationException(errorMsg, e); } catch (SignatureException e) { String errorMsg = "Signature exception occurred for Signature instance of [" + SIGNATURE_ALG + "]"; log.error(errorMsg); throw new AgentCoreOperationException(errorMsg, e); } catch (InvalidKeyException e) { String errorMsg = "InvalidKey exception occurred for signatureKey \n[\n" + signatureKey + "\n]\n"; log.error(errorMsg); throw new AgentCoreOperationException(errorMsg, e); } return signedEncodedString; }
From source file:cloud.google.oauth2.MyWayAuthentication.java
/** * Get signature from private key/*from www . j av a 2 s . c o m*/ * */ public byte[] signData(byte[] data, PrivateKey privateKey) throws InvalidKeyException, SignatureException, NoSuchAlgorithmException { Signature signature = Signature.getInstance("SHA256withRSA"); signature.initSign(privateKey); signature.update(data); return signature.sign(); }
From source file:hh.learnj.test.license.test.rsa.RSATest.java
/** * ???//from w w w. java2 s. c o m * * @param target * @return * @throws Exception */ static String signByPrivateKey(String target) throws Exception { PrivateKey privateKey = getPrivateKey(); Signature signature = Signature.getInstance(ALGORITHM_SIGN); signature.initSign(privateKey); signature.update(target.getBytes("UTF-8")); String sign = encodeBase64(signature.sign()); System.out.println("???\r\n" + sign); return sign; }
From source file:com.santander.serenity.security.credentials.bkstoken.BKSAuthenticator.java
@Override public boolean isAuthenticated(MessageContext msgCxt) { boolean isAuthenticated = false; HttpServletRequest request = (HttpServletRequest) msgCxt.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST); //Get the filesystem keystore default primary certificate KeyStoreManager keyStoreManager = KeyStoreManager.getInstance(MultitenantConstants.SUPER_TENANT_ID); BKSToken token = BKSToken.parse(request.getParameter("token")); //Validar caducidad if (System.currentTimeMillis() > token.getExpirationDate()) { log.info("BKSToken is expired"); return false; }/*from w ww .j a va 2s. c om*/ //Valida la firma try { String publicKeyAlias = token.getEmitter() + "_" + token.getSignatureMethod(); Signature verifier = Signature.getInstance(token.getSignatureMethod()); verifier.initVerify((RSAPublicKey) keyStoreManager.getPrimaryKeyStore() .getCertificate(publicKeyAlias + ".cer").getPublicKey()); verifier.update(token.getOriginalDataWithoutSignature().getBytes()); if (!verifier.verify(Base64Utils.decode(token.getSignature()))) { return false; } } catch (Exception e) { log.error(e.getMessage()); return false; } //Valida que exista el usuario en el repo de usuarios try { String userName = token.getUserId(); String tenantDomain = MultitenantUtils.getTenantDomain(userName); userName = MultitenantUtils.getTenantAwareUsername(userName); TenantManager tenantManager = BKSAuthenticatorServiceComponent.getRealmService().getTenantManager(); int tenantId = tenantManager.getTenantId(tenantDomain); if (tenantId == -1) { log.error("tenantDomain is not valid. username : " + userName + ", tenantDomain : " + tenantDomain); return false; } handleAuthenticationStarted(tenantId); UserStoreManager userStore = ((ReadWriteLDAPUserStoreManager) BKSAuthenticatorServiceComponent .getRealmService().getTenantUserRealm(tenantId).getUserStoreManager()) .getSecondaryUserStoreManager(); if (userStore.isExistingUser(userName)) { isAuthenticated = true; } if (isAuthenticated) { CarbonAuthenticationUtil.onSuccessAdminLogin(request.getSession(), userName, tenantId, tenantDomain, "BKSTToken Authentication"); handleAuthenticationCompleted(tenantId, true); return true; } else { log.error("Authentication Request is rejected. User : " + userName + " does not exists in tenant : " + tenantDomain + " 's UserStore"); CarbonAuthenticationUtil.onFailedAdminLogin(request.getSession(), userName, tenantId, "BKSToken Authentication", "User does not exists in UserStore"); handleAuthenticationCompleted(tenantId, false); return false; } } catch (Exception e) { log.error("Error authenticating the user " + e.getMessage(), e); } return isAuthenticated; }
From source file:se.curity.examples.oauth.jwt.AbstractJwtValidator.java
protected boolean validateSignature(byte[] signingInput, byte[] signature, PublicKey publicKey) { try {/*from w w w .j a va2s . c o m*/ Signature verifier = Signature.getInstance("SHA256withRSA"); verifier.initVerify(publicKey); verifier.update(signingInput); return verifier.verify(signature); } catch (Exception e) { throw new RuntimeException("Unable to validate JWT signature", e); } }
From source file:com.turo.pushy.apns.AuthenticationToken.java
public AuthenticationToken(final ApnsSigningKey signingKey, final Date issuedAt) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException { this.header = new AuthenticationTokenHeader(signingKey.getKeyId()); this.claims = new AuthenticationTokenClaims(signingKey.getTeamId(), issuedAt); final String headerJson = GSON.toJson(this.header); final String claimsJson = GSON.toJson(this.claims); final StringBuilder payloadBuilder = new StringBuilder(); payloadBuilder.append(Base64.encodeBase64URLSafeString(headerJson.getBytes(StandardCharsets.US_ASCII))); payloadBuilder.append('.'); payloadBuilder.append(Base64.encodeBase64URLSafeString(claimsJson.getBytes(StandardCharsets.US_ASCII))); {/* w w w. j ava2s . c o m*/ final Signature signature = Signature.getInstance(ApnsKey.APNS_SIGNATURE_ALGORITHM); signature.initSign(signingKey); signature.update(payloadBuilder.toString().getBytes(StandardCharsets.US_ASCII)); this.signatureBytes = signature.sign(); } payloadBuilder.append('.'); payloadBuilder.append(Base64.encodeBase64URLSafeString(this.signatureBytes)); this.base64EncodedToken = payloadBuilder.toString(); }
From source file:be.fedict.commons.eid.jca.BeIDSignature.java
@Override protected void engineInitVerify(final PublicKey publicKey) throws InvalidKeyException { LOG.debug("engineInitVerify"); if (null == this.verifySignature) { try {/* w ww .ja va 2 s .c om*/ this.verifySignature = Signature.getInstance(this.signatureAlgorithm); } catch (final NoSuchAlgorithmException nsaex) { throw new InvalidKeyException("no such algo: " + nsaex.getMessage(), nsaex); } } this.verifySignature.initVerify(publicKey); }