下面列出了 org.apache.commons.codec.binary.Base64 # decode ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* <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;
}
/**
* 使用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;
}
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;
}
@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");
}
}
@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");
}
}
@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");
}
}
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();
}
}
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.");
}
}
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");
}
}
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");
}
}
@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);
}
/**
* 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;
}
/**
* 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);
}
@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");
}
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);
}
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
}
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
}
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
}
@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);
}
@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();
}
}