Example usage for org.apache.commons.codec.binary Base64 Base64

List of usage examples for org.apache.commons.codec.binary Base64 Base64

Introduction

In this page you can find the example usage for org.apache.commons.codec.binary Base64 Base64.

Prototype

public Base64() 

Source Link

Document

Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.

Usage

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. j ava2 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.microsoft.azure.oidc.token.impl.SimpleTokenValidator.java

@Override
public Boolean validateSignature(final Token token) {
    if (token == null) {
        throw new PreconditionException("Required parameter is null");
    }/*from  www  .j av  a2s  . c o  m*/
    if (algorithmConfigurationService.get().getAlgorithmClassMap().get(token.getAlgorithm().getName())
            .equals("HMAC")) {
        return Boolean.FALSE;
    }
    final Configuration configuration = configurationCache.load();
    if (configuration == null) {
        throw new GeneralException("Error loading configuration");
    }
    try {
        final TimeStamp now = timeStampFactory.createTimeStamp(System.currentTimeMillis() / 1000);
        if (configuration.getKey(token.getKeyName()).getNotBefore().compareTo(now) > 0) {
            return Boolean.FALSE;
        }
        final Base64 decoder = new Base64();
        final BigInteger exponent = new BigInteger(1,
                decoder.decode(configuration.getKey(token.getKeyName()).getExponent().getValue()));
        final BigInteger modulus = new BigInteger(1,
                decoder.decode(configuration.getKey(token.getKeyName()).getSecret().getValue()));
        final RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(modulus, exponent);
        final KeyFactory keyFactory = KeyFactory.getInstance(
                algorithmConfigurationService.get().getAlgorithmClassMap().get(token.getAlgorithm().getName()));
        final PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);
        final Signature sig = Signature.getInstance(
                algorithmConfigurationService.get().getAlgorithmMap().get(token.getAlgorithm().getName()));
        sig.initVerify(pubKey);
        sig.update(token.getPayload().getValue().getBytes());
        return sig.verify(decoder.decode(token.getSignature().getValue()));
    } catch (NoSuchAlgorithmException | InvalidKeySpecException | SignatureException | InvalidKeyException e) {
        LOGGER.error(e.getMessage(), e);
        return Boolean.FALSE;
    }
}

From source file:com.vmware.identity.sts.auth.impl.UserCertAuthenticator.java

@Override
public Result authenticate(Request req) throws AuthenticationFailedException, UnsupportedSecurityTokenException,
        NoSuchIdPException, RequestFailedException {
    assert req != null && req.getHeader() != null;
    log.trace("Authenticating by User Cert...");

    UserCertificateTokenType userCertToken = JAXBExtractor.extractFromSecurityHeader(req.getHeader(),
            UserCertificateTokenType.class);
    if (userCertToken == null) {
        log.debug("No UserCertificateToken found!");
        return null;
    }//  w ww . ja  v  a2 s.c o m

    SignatureAlgorithmType signatureAlgorithm = userCertToken.getSignatureAlgorithm();
    BinarySecurityTokenType binarySecurityToken = userCertToken.getUserCertificate();
    String signedInfo = userCertToken.getSignatureInfo();
    SignatureValueType signatureValueType = userCertToken.getSignatureValue();
    if (signatureAlgorithm == null || binarySecurityToken == null || signedInfo == null
            || signatureValueType == null) {
        throw new InvalidCredentialsException(
                "User certificate token does not include all required information!");
    }

    if (signatureAlgorithm != SignatureAlgorithmType.SHA_256_WITH_RSA) {
        log.debug(String.format(
                "UserCertificateToken should use %s algorithm, but %s found. "
                        + "No authentication will be done",
                SignatureAlgorithmType.SHA_256_WITH_RSA.value(), signatureAlgorithm.value()));
        throw new InvalidCredentialsException(
                "User certificate token signature algorithm should be SHA256RSA!");
    }

    String userCertificate = binarySecurityToken.getValue();

    byte[] decoded = new Base64().decode(userCertificate);
    X509Certificate x509Certificate = null;
    try {
        x509Certificate = (X509Certificate) CertificateFactory.getInstance("X.509")
                .generateCertificate(new ByteArrayInputStream(decoded));
    } catch (CertificateException e) {
        throw new InvalidCredentialsException("User certificate is not valid in User certificate token");
    }

    byte[] signatureValue = signatureValueType.getValue();
    if (signatureValue == null) {
        throw new InvalidCredentialsException("Signature value is required in User certificate token!");
    }

    if (!verifyUserCertSignature(x509Certificate, signedInfo, signatureValue)) {
        throw new InvalidCredentialsException("User certificate token signature validation failed.");
    }

    PrincipalId authenticatedPrincipal = this.idmAuthenticator
            .authenticate(new X509Certificate[] { x509Certificate });

    final Date authenticationTime = new Date();
    log.debug("Authenticated principal: {} by user certificate at time: {}", authenticatedPrincipal,
            authenticationTime);

    return new Result(authenticatedPrincipal, authenticationTime, Result.AuthnMethod.SMARTCARD);
}

From source file:at.gv.egiz.sl.util.ISignatureConnectorSLWrapper.java

public byte[] sign(byte[] input, int[] byteRange, SignParameter parameter,
        RequestedSignature requestedSignature) throws PdfAsException {
    RequestPackage pack = connector.createCMSRequest(input, byteRange, parameter);
    try {/*from  ww  w. ja  v  a 2  s.  c  o m*/
        CreateCMSSignatureResponseType response = connector.sendCMSRequest(pack, parameter);

        VerifyResult verifyResult;
        try {
            verifyResult = SignatureUtils.verifySignature(response.getCMSSignature(), input);
            if (SettingsUtils.getBooleanValue(requestedSignature.getStatus().getSettings(),
                    IConfigurationConstants.KEEP_INVALID_SIGNATURE, false)) {
                Base64 b64 = new Base64();
                requestedSignature.getStatus().getMetaInformations().put(ErrorConstants.STATUS_INFO_INVALIDSIG,
                        b64.encodeToString(response.getCMSSignature()));
            }
        } catch (PDFASError e) {
            throw new PdfAsErrorCarrier(e);
        }

        if (!StreamUtils.dataCompare(requestedSignature.getCertificate().getFingerprintSHA(),
                ((X509Certificate) verifyResult.getSignerCertificate()).getFingerprintSHA())) {
            throw new PdfAsSignatureException("Certificates missmatch!");
        }

        return response.getCMSSignature();
    } finally {
        if (parameter instanceof BKUHeaderHolder) {
            BKUHeaderHolder holder = (BKUHeaderHolder) parameter;

            Iterator<BKUHeader> bkuHeaderIt = holder.getProcessInfo().iterator();

            while (bkuHeaderIt.hasNext()) {
                BKUHeader header = bkuHeaderIt.next();
                if ("Server".equalsIgnoreCase(header.getName())) {
                    requestedSignature.getStatus().getMetaInformations()
                            .put(ErrorConstants.STATUS_INFO_SIGDEVICEVERSION, header.getValue());
                } else if (ErrorConstants.STATUS_INFO_SIGDEVICE.equalsIgnoreCase(header.getName())) {
                    requestedSignature.getStatus().getMetaInformations()
                            .put(ErrorConstants.STATUS_INFO_SIGDEVICE, header.getValue());
                }
            }
        }
    }

}

From source file:com.cloudant.sync.datastore.ForceInsertTest.java

@Test
public void notification_forceinsertWithAttachmentsError() throws IOException {

    // this test only makes sense if the data is inline base64 (there's no remote server to pull the attachment from)
    boolean pullAttachmentsInline = true;

    // try and force an IOException when setting the attachment, and check everything is OK:

    // create a read only zero-length file where the extensions dir would go, to cause an IO exception
    File extensions = new File(datastore.datastoreDir + "/extensions");
    extensions.createNewFile();/*  w w w.j a  va  2 s .c  o  m*/
    extensions.setWritable(false);

    BasicDocumentRevision doc1_rev1 = datastore.createDocument(bodyOne);
    Map<String, Object> atts = new HashMap<String, Object>();
    Map<String, Object> att1 = new HashMap<String, Object>();

    atts.put("att1", att1);
    att1.put("data", new String(new Base64().encode("this is some data".getBytes())));
    att1.put("content_type", "text/plain");

    ArrayList<String> revisionHistory = new ArrayList<String>();
    revisionHistory.add(doc1_rev1.getRevision());
    doc1_rev1.setRevision("2-blah");
    revisionHistory.add(doc1_rev1.getRevision());
    // now do a force insert
    datastore.forceInsert(doc1_rev1, revisionHistory, atts, pullAttachmentsInline);

    // adding the attachment should have failed transactionally, so the rev should not exist as well
    DocumentRevision dr = datastore.getDocument(doc1_rev1.getId(), doc1_rev1.getRevision());
    Assert.assertNull("Document should not exist at this revision", dr);

    Attachment storedAtt = datastore.getAttachment(doc1_rev1, "att1");
    Assert.assertNull(storedAtt);
}

From source file:eu.aniketos.ncvm.impl.VerifyAtomic.java

/**
 * Verify an atomic service that has already been registered in the Marketplace.
 * The details for the verification should be set as class variables using the class setters.
 * @return true if the verification process verifies that the property holds for the service.
 *//*from  w w  w .  ja  v  a2 s  .c o m*/
public IVerificationResult verify() {
    IVerificationResult result = new VerificationResult();
    boolean filterMatches = (serviceFilter.isEmpty() || serviceFilter.equalsIgnoreCase(serviceID));

    if (!propertyID.equals("Confidentiality") && !propertyID.equals("DangerousFunctions")) {
        Activator.logLine("Property doesn't apply to atomic services: " + propertyID);
    }

    if (filterMatches) {
        SPState state = CacheSupport.CheckCachedProperty(call.spdm, serviceID, propertyID, result);
        if (state == SPState.Verified) {
            Activator.logLine("Property already verified and cached");
            result.setResult(1);
        } else {
            Activator.logLine("Calling PVM, service task ID: " + serviceID);
            if (call.pvm != null) {
                Base64 encoder = new Base64();
                String agreementTemplateEncoded = encoder.encodeToString(conspec.getBytes());

                try {
                    eu.aniketos.components.verification.propertyverification.PropertyVerificationResult verificationProperty = call.pvm
                            .verifyTechnicalTrustProperties(agreementTemplateEncoded, details);
                    Activator.logLine("PVM result: " + verificationProperty.getVerificationResult() + "; "
                            + verificationProperty.getVerificationExplaination());
                    int verified = verificationProperty.getVerificationResult();
                    if (verified != 0) {
                        result.setResult(0);
                        Activator.logLine("Atomic property verification unsuccessful");
                    } else {
                        result.setResult(1);
                        CacheSupport.SetCachedProperty(call.spdm, serviceID, propertyID,
                                Integer.toString(result.getResult()), SPState.Verified);
                        Activator.logLine("Atomic property verification successful, result cached in SPDM");
                    }
                } catch (Exception e) {
                    Activator.logLine("PVM error: " + e.getMessage());
                    Activator.logLine("The PVM is not accessible without authentication using dummy mode.");
                    result.setError(3, "PVM error");
                }
            } else {
                Activator.logLine("PVM not found");
                result.setError(3, "PVM not found");
            }
        }
    } else {
        Activator.logLine("ConSpec only applies to " + serviceFilter);
        Activator.logLine("Therefore skipping for " + serviceID);
        result.setResult(1);
    }

    return result;
}

From source file:lk.appzone.client.MchoiceAventuraSmsSender.java

private void setBasicAuthentication(String username, String password, HttpURLConnection connection) {

    Base64 encoder = new Base64();
    String userpassword = username + ":" + password;
    String encodedAuthorization = encoder.encodeToString((userpassword.getBytes()));
    encodedAuthorization = encodedAuthorization.substring(0, encodedAuthorization.length() - 2);

    logger.debug("base64 encoded username:password is: {}", encodedAuthorization);
    connection.setRequestProperty("Authorization", "Basic " + encodedAuthorization);

}

From source file:com.forsrc.utils.MyRsa2Utils.java

/**
 * Encrypt string./*from w w  w  .  j av a 2  s  .  co m*/
 *
 * @param publicKey the public key
 * @param plaintext the plaintext
 * @return the string
 * @throws RsaException the rsa exception
 */
public static String encrypt(PublicKey publicKey, String plaintext) throws RsaException {
    Cipher cipher = null;
    try {
        cipher = Cipher.getInstance(RsaKey.ALGORITHM, new org.bouncycastle.jce.provider.BouncyCastleProvider());
    } catch (NoSuchAlgorithmException e) {
        throw new RsaException(e);
    } catch (NoSuchPaddingException e) {
        throw new RsaException(e);
    }
    try {
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    } catch (InvalidKeyException e) {
        throw new RsaException(e);
    }
    byte[] data = plaintext.getBytes();
    int blockSize = cipher.getBlockSize();
    blockSize = blockSize == 0 ? 117 : blockSize;
    int outputSize = cipher.getOutputSize(data.length);
    int count = (int) Math.ceil(data.length / blockSize) + 1;

    byte[] output = new byte[outputSize * count];
    try {

        int i = 0;
        int start = 0;
        int outputStart = 0;
        do {
            start = i * blockSize;
            outputStart = i * outputSize;
            if (data.length - start >= blockSize) {
                cipher.doFinal(data, start, blockSize, output, outputStart);
            } else {
                cipher.doFinal(data, start, data.length - start, output, outputStart);
            }
            i++;
        } while (data.length - start - blockSize >= 0);

    } catch (IllegalBlockSizeException e) {
        throw new RsaException(e);
    } catch (BadPaddingException e) {
        throw new RsaException(e);
    } catch (ShortBufferException e) {
        throw new RsaException(e);
    }
    return new String(new Base64().encode(output));
}

From source file:com.beetle.framework.util.OtherUtil.java

public static String strBase64Encode(String str) {
    Base64 b64 = new Base64();
    byte[] b = b64.encode(str.getBytes());
    return new String(b);
}

From source file:com.aurel.track.item.AddScreenshotAction.java

public String saveScreenshot() {
    LOGGER.debug("Save screenshot workItemID=" + workItemID);
    List<LabelValueBean> errors = new ArrayList<LabelValueBean>();
    if (file == null || file.length() == 0) {
        String err = getText("common.err.required",
                new String[] { getText("report.export.manager.upload.file") });
        errors.add(new LabelValueBean(err, "file"));
        JSONUtility.encodeJSONErrors(ServletActionContext.getResponse(), errors);
        return null;
    }//from  w  w w  .j  av  a2s  . com
    if (!file.endsWith(".png")) {
        file = file + ".png";
    }
    ApplicationBean applicationBean = (ApplicationBean) application.get(Constants.APPLICATION_BEAN);
    Double maxAttachmentSizeInMb = AttachBL.getMaxAttachmentSizeInMb(applicationBean);
    int MAXFILESIZE = AttachBL.getMaxFileSize(applicationBean);
    if (maxAttachmentSizeInMb != null && Double.compare(maxAttachmentSizeInMb.doubleValue(), 0.0) != 0) {
        MAXFILESIZE = (int) (maxAttachmentSizeInMb.doubleValue() * 1024 * 1024);
    } else {
        MAXFILESIZE = 4 * 1024 * 1024;
    }
    byte[] bytearray = null;
    try {
        bytearray = new Base64().decode(bytes);
    } catch (Exception e1) {
        // TODO Auto-generated catch block
        LOGGER.error(ExceptionUtils.getStackTrace(e1));
        errors.add(new LabelValueBean(e1.getMessage(), "file"));
        JSONUtility.encodeJSONErrors(ServletActionContext.getResponse(), errors);
        return null;
    }

    if (bytearray.length > MAXFILESIZE) {
        errors.add(new LabelValueBean(
                getText("attachment.maxLengthExceeded", new String[] { maxAttachmentSizeInMb + "" }), "file"));
        JSONUtility.encodeJSONErrors(ServletActionContext.getResponse(), errors);
        return null;
    }
    int maxDescriptionSize = ApplicationBean.getInstance().getDescriptionMaxLength();
    if (description.length() > maxDescriptionSize) {
        errors.add(new LabelValueBean(getText("item.err.tooLong",
                new String[] { getText("common.lbl.description"), Integer.toString(maxDescriptionSize) }),
                "description"));
        JSONUtility.encodeJSONErrors(ServletActionContext.getResponse(), errors);
        return null;

    }
    InputStream is = new ByteArrayInputStream(bytearray);
    ApplicationBean appBean = ApplicationBean.getInstance();
    if (appBean.isBackupInProgress()) {
        errors.add(new LabelValueBean(getText("item.tabs.attachment.err.backupInProgress"), "file"));
        JSONUtility.encodeJSONErrors(ServletActionContext.getResponse(), errors);
        return null;
    }
    if (workItemID == null/*||workItemID.intValue()==-1*/) {
        HttpServletRequest request = org.apache.struts2.ServletActionContext.getRequest();
        HttpSession httpSession = request.getSession();
        WorkItemContext ctx = (WorkItemContext) session.get("workItemContext");
        if (ctx == null) {
            LOGGER.error("No context on session");
            errors.add(new LabelValueBean("No context on session", "file"));
            JSONUtility.encodeJSONErrors(ServletActionContext.getResponse(), errors);
            return null;
        }
        List<TAttachmentBean> attachments = ctx.getAttachmentsList();
        if (attachments == null) {
            attachments = new ArrayList<TAttachmentBean>();
        }
        String sessionID = httpSession.getId();
        try {
            AttachBL.saveLocal(workItemID, description, file, is, attachments, sessionID, personID);
        } catch (AttachBLException e) {
            String err = "";
            if (e.getLocalizedKey() != null) {
                err = getText(e.getLocalizedKey(), e.getLocalizedParameteres());
            } else {
                err = e.getMessage();
            }
            errors.add(new LabelValueBean(err, "file"));
            JSONUtility.encodeJSONErrors(ServletActionContext.getResponse(), errors);
            return null;

        }
        ctx.setAttachmentsList(attachments);
    } else {
        try {
            AttachBL.save(workItemID, description, file, is, personID);
            //add to history
            HistorySaverBL.addAttachment(workItemID, personID, locale, file, description,
                    Long.valueOf(bytearray.length), false);
        } catch (AttachBLException e) {
            LOGGER.error("Can't save attachemnt", e);
            String err = "";
            if (e.getLocalizedKey() != null) {
                err = getText(e.getLocalizedKey(), e.getLocalizedParameteres());
            } else {
                err = e.getMessage();
            }
            errors.add(new LabelValueBean(err, "file"));
            JSONUtility.encodeJSONErrors(ServletActionContext.getResponse(), errors);
            return null;
        }
    }
    description = null;
    JSONUtility.encodeJSONSuccess(ServletActionContext.getResponse());
    return null;
}