Java Code Examples for org.apache.commons.codec.binary.Base64#decode()

The following examples show how to use org.apache.commons.codec.binary.Base64#decode() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ZipUtils.java    From beihu-boot with Apache License 2.0 6 votes vote down vote up
/**
 * <p>Description:使用gzip进行解压缩</p>
 *
 * @param compressedStr
 * @return
 */
public static String gunzipFromByte(byte[] compressedStr) {
    if (compressedStr == null) {
        return null;
    }

    String decompressed;
    Base64 base64 = new Base64();
    try (ByteArrayInputStream in = new ByteArrayInputStream(base64.decode(compressedStr));
         GZIPInputStream ginzip = new GZIPInputStream(in);
         ByteArrayOutputStream out = new ByteArrayOutputStream()) {

        byte[] buffer = new byte[1024];
        int offset = -1;
        while ((offset = ginzip.read(buffer)) != -1) {
            out.write(buffer, 0, offset);
        }
        decompressed = new String(out.toByteArray());
    } catch (IOException e) {
        decompressed = null;
    }

    return decompressed;
}
 
Example 2
Source File: CuentasContablesv11.java    From factura-electronica with Apache License 2.0 6 votes vote down vote up
public void verificar() throws Exception {
	String certStr = document.getCertificado();
	Base64 b64 = new Base64();
	byte[] cbs = b64.decode(certStr);

	X509Certificate cert = KeyLoaderFactory.createInstance(KeyLoaderEnumeration.PUBLIC_KEY_LOADER,new ByteArrayInputStream(cbs)).getKey();

	String sigStr = document.getSello();
	byte[] signature = b64.decode(sigStr); 
	byte[] bytes = getOriginalBytes();
	Signature sig = Signature.getInstance("SHA1withRSA");
	sig.initVerify(cert);
	sig.update(bytes);
	boolean bool = sig.verify(signature);
	if (!bool) {
		throw new Exception("Invalid signature");
	}
}
 
Example 3
Source File: BalanzaComprobacionv11.java    From factura-electronica with Apache License 2.0 6 votes vote down vote up
public void verificar() throws Exception {
	String certStr = document.getCertificado();
	Base64 b64 = new Base64();
	byte[] cbs = b64.decode(certStr);

	X509Certificate cert = KeyLoaderFactory.createInstance(KeyLoaderEnumeration.PUBLIC_KEY_LOADER,new ByteArrayInputStream(cbs)).getKey();

	String sigStr = document.getSello();
	byte[] signature = b64.decode(sigStr); 
	byte[] bytes = getOriginalBytes();
	Signature sig = Signature.getInstance("SHA1withRSA");
	sig.initVerify(cert);
	sig.update(bytes);
	boolean bool = sig.verify(signature);
	if (!bool) {
		throw new Exception("Invalid signature");
	}
}
 
Example 4
Source File: CFDv2.java    From factura-electronica with Apache License 2.0 6 votes vote down vote up
public void verificar(InputStream in) throws Exception {
    String certStr = document.getCertificado();
    Base64 b64 = new Base64();
    byte[] cbs = b64.decode(certStr);

    X509Certificate cert = KeyLoaderFactory.createInstance(
            KeyLoaderEnumeration.PUBLIC_KEY_LOADER,
            new ByteArrayInputStream(cbs)
    ).getKey();

    String sigStr = document.getSello();
    byte[] signature = b64.decode(sigStr);
    byte[] bytes = getOriginalBytes(in);
    Signature sig = Signature.getInstance("SHA1withRSA");
    sig.initVerify(cert);
    sig.update(bytes);
    boolean bool = sig.verify(signature);
    if (!bool) {
        throw new Exception("Invalid signature.");
    }
}
 
Example 5
Source File: ScreenShot.java    From wd.java with MIT License 6 votes vote down vote up
public void saveScreenshot(String filename) throws Exception {
    Base64 decoder = new Base64();
    try {
        // Decode Base64
        byte[] b = decoder.decode(takeScreenshot().toString());
        for (int i = 0; i < b.length; ++i) {
            if (b[i] < 0) {
                b[i] += 256;
            }
        }
        // generate the image file
        FileOutputStream out = new FileOutputStream(filename);
        int n = 0;
        byte[] bb = new byte[1024];
        out.write(b);
        out.flush();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 6
Source File: CFDv32.java    From factura-electronica with Apache License 2.0 6 votes vote down vote up
@Override
public void verificar() throws Exception {
    String certStr = document.getCertificado();
    Base64 b64 = new Base64();
    byte[] cbs = b64.decode(certStr);

    X509Certificate cert = KeyLoaderFactory.createInstance(
            KeyLoaderEnumeration.PUBLIC_KEY_LOADER,
            new ByteArrayInputStream(cbs)
    ).getKey();

    String sigStr = document.getSello();
    byte[] signature = b64.decode(sigStr);
    byte[] bytes = getOriginalBytes();
    Signature sig = Signature.getInstance("SHA1withRSA");
    sig.initVerify(cert);
    sig.update(bytes);
    boolean bool = sig.verify(signature);
    if (!bool) {
        throw new Exception("Invalid signature");
    }
}
 
Example 7
Source File: CFDv3.java    From factura-electronica with Apache License 2.0 6 votes vote down vote up
@Override
public void verificar() throws Exception {
    String certStr = document.getCertificado();
    Base64 b64 = new Base64();
    byte[] cbs = b64.decode(certStr);

    X509Certificate cert = KeyLoaderFactory.createInstance(
            KeyLoaderEnumeration.PUBLIC_KEY_LOADER,
            new ByteArrayInputStream(cbs)
    ).getKey();

    String sigStr = document.getSello();
    byte[] signature = b64.decode(sigStr);
    byte[] bytes = getOriginalBytes();
    Signature sig = Signature.getInstance("SHA1withRSA");
    sig.initVerify(cert);
    sig.update(bytes);
    boolean bool = sig.verify(signature);
    if (!bool) {
        throw new Exception("Invalid signature");
    }
}
 
Example 8
Source File: CFDv33.java    From factura-electronica with Apache License 2.0 6 votes vote down vote up
@Override
public void verificar() throws Exception {
    String certStr = document.getCertificado();
    Base64 b64 = new Base64();
    byte[] cbs = b64.decode(certStr);

    X509Certificate cert = KeyLoaderFactory.createInstance(
            KeyLoaderEnumeration.PUBLIC_KEY_LOADER,
            new ByteArrayInputStream(cbs)
    ).getKey();

    String sigStr = document.getSello();
    byte[] signature = b64.decode(sigStr);
    byte[] bytes = getOriginalBytes();
    Signature sig = Signature.getInstance("SHA256withRSA");
    sig.initVerify(cert);
    sig.update(bytes);
    boolean bool = sig.verify(signature);
    if (!bool) {
        throw new Exception("Invalid signature");
    }
}
 
Example 9
Source File: AuthChecks.java    From xian with Apache License 2.0 6 votes vote down vote up
protected String getBasicAuthenticationClientId(HttpRequest req) {
    // extract Basic Authentication header
    String authHeader = req.headers().get(HttpHeaders.AUTHORIZATION);
    String clientId = null;
    if (authHeader != null && authHeader.contains(BASIC)) {
        String value = authHeader.replace(BASIC, "");
        Base64 decoder = new Base64();
        byte[] decodedBytes = decoder.decode(value);
        String decoded = new String(decodedBytes);
        // client_id:client_secret
        String[] str = decoded.split(":");
        if (str.length == 2) {
            String authClientId = str[0];
            String authClientSecret = str[1];
            // check valid - DB call
            if (db.validClient(authClientId, authClientSecret).blockingGet()) {
                clientId = authClientId;
            }
        }
    }
    return clientId;
}
 
Example 10
Source File: ZipUtils.java    From beihu-boot with Apache License 2.0 6 votes vote down vote up
/**
 * 使用zip进行解压缩
 *
 * @param compressedStr 压缩后的文本
 * @return 解压后的字符串
 */
public static String unzip(String compressedStr) {
    if (compressedStr == null) {
        return null;
    }

    byte[] compressed = null;
    String decompressed = null;
    Base64 base64 = new Base64();
    compressed = base64.decode(compressedStr);
    try (ByteArrayOutputStream out = new ByteArrayOutputStream();
         ByteArrayInputStream in = new ByteArrayInputStream(compressed);
         ZipInputStream zin = new ZipInputStream(in)) {
        zin.getNextEntry();
        byte[] buffer = new byte[1024];
        int offset = -1;
        while ((offset = zin.read(buffer)) != -1) {
            out.write(buffer, 0, offset);
        }
        decompressed = new String(out.toByteArray());
    } catch (IOException e) {
        decompressed = null;
    }
    return decompressed;
}
 
Example 11
Source File: FileServiceTestCase.java    From product-ei with Apache License 2.0 5 votes vote down vote up
@Test(groups = {"wso2.dss"}, dependsOnMethods = {"createNewFile"})
    public void addRecord() throws IOException, XPathExpressionException {
        OMElement payload = fac.createOMElement("_postappenddatatofile", omNs);
        String recordsExpected = "";

        OMElement fileName = fac.createOMElement("fileName", omNs);
        fileName.setText(txtFileName);
        payload.addChild(fileName);

        OMElement fileRecord = fac.createOMElement("data", omNs);
        AxisServiceClient axisClient = new AxisServiceClient();
        Base64 encoder = new Base64();
//        encoder.e
//        BASE64Decoder decoder = new BASE64Decoder();
        for (int i = 0; i < 5; i++) {
            String record = "TestFileRecord" + i;
            fileRecord.setText(new String(encoder.encode(record.getBytes())));
            payload.addChild(fileRecord);
            recordsExpected = recordsExpected + record + ";";
            axisClient.sendRobust(payload, getServiceUrlHttp(serviceName), "_postappenddatatofile");

        }
        log.info("Records Added");
        OMElement response = getRecord();
        Iterator file = response.getChildrenWithLocalName("File");
        String recordData = "";
        while (file.hasNext()) {
            OMElement data = (OMElement) file.next();
            recordData = recordData + new String(encoder.decode(data.getFirstElement().getText().getBytes())) + ";";

        }
        Assert.assertNotSame("", recordsExpected, "No Record added to file. add records to file");
        Assert.assertEquals(recordData, recordsExpected, "Record Data Mismatched");
    }
 
Example 12
Source File: Token.java    From big-c with Apache License 2.0 5 votes vote down vote up
/**
 * Modify the writable to the value from the newValue
 * @param obj the object to read into
 * @param newValue the string with the url-safe base64 encoded bytes
 * @throws IOException
 */
private static void decodeWritable(Writable obj, 
                                   String newValue) throws IOException {
  Base64 decoder = new Base64(0, null, true);
  DataInputBuffer buf = new DataInputBuffer();
  byte[] decoded = decoder.decode(newValue);
  buf.reset(decoded, decoded.length);
  obj.readFields(buf);
}
 
Example 13
Source File: TeaUtil.java    From yunpian-java-sdk with MIT License 5 votes vote down vote up
public static String decryptForYunpianV2(String msg, String secret) throws IOException {
	int[] key = getKeyByApikey(secret + secret + secret + secret);
	// byte[] secretInfo = Base64.decodeBase64(secret);
	Base64 base64 = new Base64();
	byte[] secretInfo = base64.decode(msg);
	return decryptByTea(secretInfo, key);
}
 
Example 14
Source File: TFDv1.java    From factura-electronica with Apache License 2.0 5 votes vote down vote up
public int verificar() throws Exception {
    if (tfd == null) {
        return 601; //No contiene timbrado
    }
    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
}
 
Example 15
Source File: TFDv11.java    From factura-electronica with Apache License 2.0 5 votes vote down vote up
public int verificar() throws Exception {
    if (tfd == null) {
        return 601; //No contiene timbrado
    }
    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
}
 
Example 16
Source File: TFDv1c32.java    From factura-electronica with Apache License 2.0 5 votes vote down vote up
public int verificar() throws Exception {
    if (tfd == null) {
        return 601; //No contiene timbrado
    }
    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
}
 
Example 17
Source File: OidcHelper.java    From entando-components with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Attempts to find a user in the Entando database for the username found in the accesstoken. If none is found,
 * it constructs an in-memory UserDetails object and populates its attributes from attribytes found in
 * the token.
 * @param accessToken
 * @return
 * @throws ApsSystemException
 */
public UserDetails getOidcUser(String accessToken) throws ApsSystemException {
    String[] split_string = accessToken.split("\\.");
    String base64EncodedBody = split_string[1];
    Base64 base64Url = new Base64(true);
    logger.info("---------------------TOKEN-----------------------");
    logger.info(new String(base64Url.decode(split_string[0])));
    logger.info("--------------------------------------------");
    String body = new String(base64Url.decode(base64EncodedBody));
    logger.info(body);
    logger.info("--------------------------------------------");
    JSONObject obj = new JSONObject(body);
    String username = null;
    if (obj.has(USERNAME_PARAM_NAME)) {
        username = obj.getString(USERNAME_PARAM_NAME);
        logger.info("USERNAME -> " + username);
    } else {
        username = "tempUser";
        logger.info("\"" + USERNAME_PARAM_NAME + "\" ATTRIBUTE NOT FOUND");
        logger.info("DEFAULT USERNAME -> " + username);
    }
    if (StringUtils.isEmpty(username)) {
        username = "tempUser";
        logger.info("\"" + USERNAME_PARAM_NAME + "\" ATTRIBUTE EMPTY OR NOT FOUND");
        logger.info("DEFAULT USERNAME -> " + username);
    }
    UserDetails user = authenticationProviderManager.getUser(username);
    if (null == user) {
        logger.info("CREATING UserDetails object for  " + username);
        user = new User();
        ((User) user).setUsername(username);
        ((User) user).setPassword(RESERVED_PASSWORD);
        UserProfile profile = new UserProfile();
        ((User) user).setProfile(profile);
        copyAttributes(obj, profile);
    }else{
        logger.info("WARNING!!! UserDetails object found for  " + username);
    }
    return user;
}
 
Example 18
Source File: CFDv2.java    From factura-electronica with Apache License 2.0 5 votes vote down vote up
@Override
public void verificar() throws Exception {
    String certStr = document.getCertificado();
    Base64 b64 = new Base64();
    byte[] cbs = b64.decode(certStr);

    X509Certificate cert = KeyLoaderFactory.createInstance(
            KeyLoaderEnumeration.PUBLIC_KEY_LOADER,
            new ByteArrayInputStream(cbs)
    ).getKey();

    verificar(cert);
}
 
Example 19
Source File: ApacheCommonsEncodeDecodeUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenStringIsEncoded_thenStringCanBeDecoded() throws UnsupportedEncodingException {
    final String originalInput = "test input";
    final Base64 base64 = new Base64();
    final String encodedString = new String(base64.encode(originalInput.getBytes()));

    final String decodedString = new String(base64.decode(encodedString.getBytes()));

    assertNotNull(decodedString);
    assertEquals(originalInput, decodedString);
}
 
Example 20
Source File: Assignments.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
@WebMethod
@Path("/addSubmissionAttachment")
@Produces("text/plain")
@GET
public String addSubmissionAttachment(
        @WebParam(name = "sessionId", partName = "sessionId") @QueryParam("sessionId") String sessionId,
        @WebParam(name = "context", partName = "context") @QueryParam("context") String context,
        @WebParam(name = "submissionId", partName = "submissionId") @QueryParam("submissionId") String submissionId,
        @WebParam(name = "attachmentName", partName = "attachmentName") @QueryParam("attachmentName") String attachmentName,
        @WebParam(name = "attachmentMimeType", partName = "attachmentMimeType") @QueryParam("attachmentMimeType") String attachmentMimeType,
        @WebParam(name = "attachmentData", partName = "attachmentData") @QueryParam("attachmentData") String attachmentData) {


    try {
		// establish the session
		Session s = establishSession(sessionId);
		AssignmentSubmission sub = assignmentService.getSubmission(submissionId);
		
		// create the attachmment
		Base64 decode = new Base64();
		// byte[] photoData = null;
		// photoData = decode.decodeToByteArray(attachmentData);
		byte[] photoData = decode.decode(attachmentData);
		log.info("File of size: " + photoData + " found");
		
		byte[] content = photoData;
				
		ResourcePropertiesEdit rpe = contentHostingService.newResourceProperties();
		rpe.addProperty(rpe.PROP_DISPLAY_NAME, attachmentName);
		
		ContentResource file = contentHostingService.addAttachmentResource(attachmentName,
				context, "Assignments", attachmentMimeType, content, rpe);
		log.info("attachment name is : " + attachmentName);
		log.info("file has lenght of: " + file.getContentLength());
		
		Reference ref = entityManager.newReference(file.getReference());
		sub.getAttachments().add(ref.getReference());
		assignmentService.updateSubmission(sub);
		return "Success!";
	} catch (Exception e) {
		log.error("WS addSubmissionAttachment(): " + e.getClass().getName() + " : " + e.getMessage()); 
        return e.getClass().getName() + " : " + e.getMessage();
	}
	
}