List of usage examples for java.security Signature initVerify
public final void initVerify(Certificate certificate) throws InvalidKeyException
From source file:mx.bigdata.cfdi.TFDv1.java
public int verify(Certificate cert) throws Exception { if (tfd == null) { return 601; //No contiene timbrado }/*ww w . ja va2s . c o m*/ Base64 b64 = new Base64(); String sigStr = tfd.getSelloSAT(); byte[] signature = b64.decode(sigStr); byte[] bytes = getOriginalBytes(); Signature sig = Signature.getInstance("SHA1withRSA"); sig.initVerify(cert); sig.update(bytes); boolean verified = sig.verify(signature); return verified ? 600 : 602; //Sello del timbrado no valido }
From source file:mx.bigdata.sat.cfdi.TFDv11c33.java
public int verificar() throws Exception { if (tfd == null) { return 601; //No contiene timbrado }/*from ww w . java 2 s . c o m*/ Base64 b64 = new Base64(); String sigStr = tfd.getSelloSAT(); byte[] signature = b64.decode(sigStr); byte[] bytes = getOriginalBytes(); Signature sig = Signature.getInstance("SHA256withRSA"); sig.initVerify(cert); sig.update(bytes); boolean verified = sig.verify(signature); return verified ? 600 : 602; //Sello del timbrado no valido }
From source file:com.xk72.cocoafob.LicenseGenerator.java
/** * Verify the given license for the given {@link LicenseData}. * @param licenseData// ww w .jav a 2 s .c o m * @param license * @return Whether the license verified successfully. * @throws LicenseGeneratorException If the verification encounters an error, usually due to invalid input. You MUST check the return value of this method if no exception is thrown. * @throws IllegalStateException If the generator is not setup correctly to verify licenses. */ public boolean verifyLicense(LicenseData licenseData, String license) throws LicenseGeneratorException, IllegalStateException { if (!isCanVerifyLicenses()) { throw new IllegalStateException( "The LicenseGenerator cannot verify licenses as it was not configured with a public key"); } final String stringData = licenseData.toLicenseStringData(); /* replace O with 8 and I with 9 */ String licenseSignature = license.replace("8", "O").replace("9", "I"); /* remove dashes */ licenseSignature = licenseSignature.replace("-", ""); /* Pad the output length to a multiple of 8 with '=' characters */ while (licenseSignature.length() % 8 != 0) { licenseSignature += "="; } byte[] decoded = new Base32().decode(licenseSignature); try { Signature dsa = Signature.getInstance("SHA1withDSA", "SUN"); dsa.initVerify(publicKey); dsa.update(stringData.getBytes("UTF-8")); return dsa.verify(decoded); } catch (NoSuchAlgorithmException e) { throw new LicenseGeneratorException(e); } catch (NoSuchProviderException e) { throw new LicenseGeneratorException(e); } catch (InvalidKeyException e) { throw new LicenseGeneratorException(e); } catch (SignatureException e) { throw new LicenseGeneratorException(e); } catch (UnsupportedEncodingException e) { throw new LicenseGeneratorException(e); } }
From source file:com.tenduke.example.scribeoauth.JwtLoginServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * * @param request servlet request/*ww w . j ava 2 s .c o m*/ * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { // String idToken = request.getParameter(PARAMETER_NAME_ID_TOKEN); // // check that parameter is ~OK. if (idToken != null && !idToken.isEmpty() && idToken.indexOf(".") > 0) { // // JWT has 3 elements, which are separated by a "." char. String[] jwtElements = idToken.split("\\."); if (jwtElements.length == 3) { // String header = jwtElements[0]; String body = jwtElements[1]; byte[] dataBytes = new StringBuilder(header).append(".").append(body).toString().getBytes("UTF-8"); byte[] signatureBytes = Base64.decodeBase64(jwtElements[2]); // try { // java.security.Signature signature = java.security.Signature.getInstance("SHA256withRSA"); signature.initVerify(publicKey); // signature.update(dataBytes); // if (signature.verify(signatureBytes)) { // doLogin(request, response, new String(Base64.decodeBase64(body), "UTF-8")); } } catch (InvalidKeyException | NoSuchAlgorithmException | SignatureException ex) { // throw new ServletException( "No way, basic RSA based key handling and signature verification failed...", ex); } } else { // throw new ServletException("Unexpected JWT data"); } } else { // throw new ServletException("Request parameter: " + PARAMETER_NAME_ID_TOKEN + " not given"); } }
From source file:Version2LicenseDecoder.java
private byte[] checkAndGetLicenseText(String licenseContent) { try {//w ww . j ava 2s . c om byte[] e = Base64.decodeBase64(licenseContent.getBytes()); ByteArrayInputStream in = new ByteArrayInputStream(e); DataInputStream dIn = new DataInputStream(in); int textLength = dIn.readInt(); byte[] licenseText = new byte[textLength]; dIn.read(licenseText); byte[] hash = new byte[dIn.available()]; dIn.read(hash); try { Signature e1 = Signature.getInstance("SHA1withDSA"); e1.initVerify(PUBLIC_KEY); e1.update(licenseText); if (!e1.verify(hash)) { throw new LicenseException("Failed to verify the license."); } else { return licenseText; } } catch (InvalidKeyException var9) { throw new LicenseException(var9); } catch (SignatureException var10) { throw new LicenseException(var10); } catch (NoSuchAlgorithmException var11) { throw new LicenseException(var11); } } catch (IOException var12) { throw new LicenseException(var12); } }
From source file:org.p2pvpn.tools.AdvProperties.java
/** * Verify a signature.// ww w . j a v a 2s . c o m * @param keyName name if the signature key. * @param publicKey the public key of the signature * @return signature correct? */ public boolean verify(String keyName, PublicKey publicKey) { try { byte[] data = filter(keyName, true).asBytes(); Signature signature = CryptoUtils.getSignature(); signature.initVerify(publicKey); signature.update(data); return signature.verify(getPropertyBytes(keyName, null)); } catch (Throwable ex) { Logger.getLogger("").log(Level.SEVERE, null, ex); return false; } }
From source file:com.cedarsoft.crypt.X509Support.java
/** * <p>verifySignature</p>//from w ww . j a va 2 s . c o m * * @param plainText an array of byte. * @param signature a com.cedarsoft.crypt.Signature object. * @return a boolean. * * @throws GeneralSecurityException * if any. */ public boolean verifySignature(@Nonnull byte[] plainText, @Nonnull com.cedarsoft.crypt.Signature signature) throws GeneralSecurityException { Signature sign = Signature.getInstance(SHA_256_WITH_RSA); sign.initVerify(certificate); sign.update(plainText); return sign.verify(signature.getBytes()); }
From source file:com.turo.pushy.apns.AuthenticationToken.java
public boolean verifySignature(final ApnsVerificationKey verificationKey) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException { if (!this.header.getKeyId().equals(verificationKey.getKeyId())) { return false; }//from w w w. j a v a 2 s .c o m if (!this.claims.getIssuer().equals(verificationKey.getTeamId())) { return false; } final byte[] headerAndClaimsBytes; final String headerJson = GSON.toJson(this.header); final String claimsJson = GSON.toJson(this.claims); final StringBuilder headerAndClaimsBuilder = new StringBuilder(); headerAndClaimsBuilder .append(Base64.encodeBase64URLSafeString(headerJson.getBytes(StandardCharsets.US_ASCII))); headerAndClaimsBuilder.append('.'); headerAndClaimsBuilder .append(Base64.encodeBase64URLSafeString(claimsJson.getBytes(StandardCharsets.US_ASCII))); headerAndClaimsBytes = headerAndClaimsBuilder.toString().getBytes(StandardCharsets.US_ASCII); final Signature signature = Signature.getInstance(ApnsKey.APNS_SIGNATURE_ALGORITHM); signature.initVerify(verificationKey); signature.update(headerAndClaimsBytes); return signature.verify(this.signatureBytes); }
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 va2 s.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:mx.bigdata.sat.cfd.CFDv2.java
public void verificar(Certificate cert) throws Exception { String sigStr = document.getSello(); Base64 b64 = new Base64(); byte[] signature = b64.decode(sigStr); byte[] bytes = getOriginalBytes(); boolean md5 = true; if (getYear() < 2011) { Signature sig = Signature.getInstance("MD5withRSA"); sig.initVerify(cert); sig.update(bytes);/*from w w w.j ava2 s . co m*/ try { sig.verify(signature); } catch (SignatureException e) { // Not MD5 md5 = false; } } if (getYear() > 2010 || !md5) { Signature sig = Signature.getInstance("SHA1withRSA"); sig.initVerify(cert); sig.update(bytes); boolean bool = sig.verify(signature); if (!bool) { throw new Exception("Invalid signature"); } } }