下面列出了 org.apache.commons.codec.binary.Base64 # encodeBase64String ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static String getInMemoryLogs(boolean compress) {
Logger logger = (ch.qos.logback.classic.Logger)LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
IrisAgentAppender appender = (com.iris.agent.logging.IrisAgentAppender)logger.getAppender("MEMORY");
if (appender == null) {
return "";
}
String logs = appender.getLogs();
if (!compress) {
return logs;
}
byte[] data = logs.getBytes(StandardCharsets.UTF_8);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (GZIPOutputStream os = new GZIPOutputStream(baos)) {
os.write(data);
} catch (Exception ex) {
}
byte[] compressed = baos.toByteArray();
return Base64.encodeBase64String(compressed);
}
public String prepareDownload(AuthenticateClientSmDp authenticateClientSmDp) {
progress.setCurrentPhase(DownloadProgressPhase.DOWNLOADING);
progress.stepExecuted(ProgressStep.DOWNLOAD_PROFILE_PREPARE_DOWNLOAD, "prepareDownload retrieving...");
String prepareDownloadResponse = apduTransmitter.transmitApdus(ApduUtils.prepareDownloadApdu(authenticateClientSmDp.getSmdpSigned2(),
authenticateClientSmDp.getSmdpSignature2(), authenticateClientSmDp.getSmdpCertificate(),
null));
String encodedPrepareDownloadResponse = Base64.encodeBase64String(Util.hexStringToByteArray(prepareDownloadResponse));
if (LogStub.getInstance().isDebugEnabled()) {
LogStub.getInstance().logDebug(LOG, LogStub.getInstance().getTag() + " - Prepare download response (base64): " + encodedPrepareDownloadResponse);
}
progress.stepExecuted(ProgressStep.DOWNLOAD_PROFILE_PREPARED_DOWNLOAD, "prepareDownload retrieved...");
return encodedPrepareDownloadResponse;
}
@Override
protected String encryptValue(EncryptMethod encryptMethod, byte[] key, byte[] objBytes) throws GeneralException {
byte[] saltBytes;
switch (encryptMethod) {
case SALT:
Random random = new SecureRandom();
// random length 5-16
saltBytes = new byte[5 + random.nextInt(11)];
random.nextBytes(saltBytes);
break;
default:
saltBytes = new byte[0];
break;
}
byte[] allBytes = new byte[1 + saltBytes.length + objBytes.length];
allBytes[0] = (byte) saltBytes.length;
System.arraycopy(saltBytes, 0, allBytes, 1, saltBytes.length);
System.arraycopy(objBytes, 0, allBytes, 1 + saltBytes.length, objBytes.length);
@SuppressWarnings("deprecation") // SCIPIO: 2018-11-22: DES encrypt calls logged as warnings, so no need for source warnings
String result = Base64.encodeBase64String(DesCrypt.encrypt(DesCrypt.getDesKey(key), allBytes));
return result;
}
private void retrieveNewAccessToken() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
final String authString = jHipsterProperties.getSecurity().getClientAuthorization().getClientId() + ":" + jHipsterProperties.getSecurity().getClientAuthorization().getClientSecret();
final String authorization = "Basic " + Base64.encodeBase64String(authString.getBytes());
headers.add("Authorization", authorization);
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("grant_type", "client_credentials");
HttpEntity<?> requestEntity = new HttpEntity<>(map, headers);
String uaaServiceId = jHipsterProperties.getSecurity().getClientAuthorization().getTokenServiceId();
ResponseEntity<DefaultOAuth2AccessToken> responseEntity = this.restTemplate.exchange("http://" + uaaServiceId + "/oauth/token", HttpMethod.POST, requestEntity, DefaultOAuth2AccessToken.class);
if (!responseEntity.getStatusCode().is2xxSuccessful()) {
//TODO
}
accessToken = Objects.requireNonNull(responseEntity.getBody()).getValue();
}
public static void setupDefaultService() {
final String remoteServices = ProgramProperties.get("RemoteServers", "");
if (!remoteServices.contains(DEFAULT_MEGAN_SERVER)) {
final String user = "guest";
final String encodedPassword = Base64.encodeBase64String("guest".getBytes());
if (remoteServices.length() == 0)
ProgramProperties.put("RemoteServers", DEFAULT_MEGAN_SERVER);
else
ProgramProperties.put("RemoteServers", remoteServices + "%%%" + DEFAULT_MEGAN_SERVER);
final List<String> credentials = new LinkedList<>(Arrays.asList(ProgramProperties.get("MeganServerCredentials", new String[0])));
credentials.add(DEFAULT_MEGAN_SERVER + "::" + user + "::" + encodedPassword);
ProgramProperties.put("MeganServerCredentials", credentials.toArray(new String[0]));
}
}
/**
* Generates signature info.
*
* @param request The HTTP request.
* @param apiSecret API secret.
* @param timestamp Timestamp.
* @return THe signature.
*/
public static String genSignature(Request request, String apiSecret, String timestamp) {
String endpoint = request.url().encodedPath();
String requestUriParams = request.url().query();
String requestBody = getRequestBody(request);
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(timestamp);
stringBuilder.append(request.method());
stringBuilder.append(endpoint);
stringBuilder.append((StringUtils.isBlank(requestUriParams) ? "" : "?" + requestUriParams));
stringBuilder.append((StringUtils.isBlank(requestBody) ? "" : "" + requestBody));
String originToSign = stringBuilder.toString();
String signature = Base64.encodeBase64String(HmacUtils.hmacSha256(apiSecret, originToSign));
LOGGER.debug("originToSign={}", originToSign);
LOGGER.debug("method={},endpoint={}", request.method(), endpoint);
LOGGER.debug("signature={}", signature);
return signature;
}
ActionResult<Wo> execute(EffectivePerson effectivePerson, String id, Integer scale) throws Exception {
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
ActionResult<Wo> result = new ActionResult<>();
Attachment2 attachment = emc.find(id, Attachment2.class, ExceptionWhen.not_found);
/* 判断文件的当前用户是否是管理员或者文件创建者 或者当前用户在分享或者共同编辑中 */
if (effectivePerson.isNotManager() && effectivePerson.isNotPerson(attachment.getPerson())) {
throw new Exception("person{name:" + effectivePerson.getDistinguishedName() + "} access attachment{id:"
+ id + "} denied.");
}
if (!ArrayUtils.contains(IMAGE_EXTENSIONS, attachment.getExtension())) {
throw new Exception("attachment not image file.");
}
if (scale < 0 || scale > 100) {
throw new Exception("invaild scale:" + scale + ".");
}
OriginFile originFile = emc.find(attachment.getOriginFile(),OriginFile.class);
if (null == originFile) {
throw new ExceptionAttachmentNotExist(id,attachment.getOriginFile());
}
StorageMapping mapping = ThisApplication.context().storageMappings().get(OriginFile.class,
originFile.getStorage());
try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
originFile.readContent(mapping, output);
try (ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray())) {
BufferedImage src = ImageIO.read(input);
int width = (src.getWidth() * scale) / (int) 100;
int height = (src.getHeight() * scale) / (int) 100;
BufferedImage scalrImage = Scalr.resize(src, width, height);
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
ImageIO.write(scalrImage, "png", baos);
String str = Base64.encodeBase64String(baos.toByteArray());
Wo wo = new Wo();
wo.setValue(str);
result.setData(wo);
}
}
}
return result;
}
}
public static String getObjectToSign(String ApplicationParam, String ChallengeParam, String kh, String PublicKey) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException {
byte[] constant = {(byte) 0x00};
int constantL = constant.length;
byte[] Challenge = Base64.decodeBase64(ChallengeParam);
int ChanllengeL = Challenge.length;
byte[] Application = Base64.decodeBase64(ApplicationParam);
int ApplicationL = Application.length;
byte[] keyHandle = Base64.decodeBase64(kh);
int keyHandleL = keyHandle.length;
byte[] publicKey = Base64.decodeBase64(PublicKey);
int publicKeyL = publicKey.length;
/////////
//Convert back to publicKey
KeyFactory kf = KeyFactory.getInstance("ECDSA", "BCFIPS");
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(publicKey);
PublicKey pub = kf.generatePublic(pubKeySpec);
int pukL = CSConstants.EC_P256_PUBLICKKEYSIZE;
//Create byte[] Object to sign
byte[] ob2Sign = new byte[constantL + ChanllengeL + ApplicationL + keyHandleL + pukL];
//copy constant
int tot = 0;
System.arraycopy(constant, 0, ob2Sign, tot, constantL);
tot += constantL;
System.arraycopy(Application, 0, ob2Sign, tot, ApplicationL);
tot += ApplicationL;
System.arraycopy(Challenge, 0, ob2Sign, tot, ChanllengeL);
tot += ChanllengeL;
System.arraycopy(keyHandle, 0, ob2Sign, tot, keyHandleL);
tot += keyHandleL;
System.arraycopy(publicKey, 0, ob2Sign, tot, pukL);
tot += pukL;
return Base64.encodeBase64String(ob2Sign);
}
/**
* 银行卡识别,使用Base64编码后的文件方式,使用Token认证方式访问服务
* @param token token认证串
* @param formFile 文件路径
* @throws IOException
*/
public static void requestOcrBankCardBase64(String token, String formFile) {
// 1.构建银行卡识别服务所需要的参数
String url = "https://ais.cn-north-1.myhuaweicloud.com/v1.0/ocr/bank-card";
Header[] headers = new Header[] {new BasicHeader("X-Auth-Token", token), new BasicHeader("Content-Type", ContentType.APPLICATION_JSON.toString()) };
try {
byte[] fileData = FileUtils.readFileToByteArray(new File(formFile));
String fileBase64Str = Base64.encodeBase64String(fileData);
JSONObject json = new JSONObject();
json.put("image", fileBase64Str);
//图片的URL路径, 与image参数是二选一关系,目前仅支持华为云上OBS提供的临时授权或者匿名公开授权访问的URL。
//json.put("url", "http://obs.myhuaweicloud.com/ObjectKey?AWSAccessKeyId=AccessKeyID"
// + "&Expires=ExpiresValue&Signature=signature");
//
// 1.a 此项参数可选,是否支持返回发卡机构信息, 默认不返回。
// true: 支持。false: 不支持,默认不支持。
//
//json.put("issue", true);
StringEntity stringEntity = new StringEntity(json.toJSONString(), "utf-8");
// 3.传入银行卡识别服务对应的uri参数, 传入银行卡识别服务需要的参数,
// 该参数主要通过JSON对象的方式传入, 使用POST方法调用服务
HttpResponse response = HttpClientUtils.post(url, headers, stringEntity);
// 4.验证服务调用返回的状态是否成功,如果为200, 为成功, 否则失败。
ResponseProcessUtils.processResponseStatus(response);
// 5.处理服务返回的字符流。
ResponseProcessUtils.processResponse(response);
} catch (Exception e) {
e.printStackTrace();
}
}
public String encryptText(String text) throws FileIOException
{
final ByteArrayOutputStream output = new ByteArrayOutputStream();
final byte[] bytes = text.getBytes();
_encryptData(output, new ByteArrayInputStream(bytes), bytes.length, PGPLiteralData.CONSOLE, null, ENCRYPT_ALGORITHM, ENCRYPT_ARMOR);
text = Base64.encodeBase64String(output.toByteArray());
text = text.replace('/', '_');
return text;
}
/**
* Create a logout message for front channel logout.
*
* @param logoutRequest the logout request.
* @return a front SAML logout message.
*/
public String createFrontChannelLogoutMessage(final LogoutRequest logoutRequest) {
final String logoutMessage = this.logoutMessageBuilder.create(logoutRequest);
final Deflater deflater = new Deflater();
deflater.setInput(logoutMessage.getBytes(ASCII));
deflater.finish();
final byte[] buffer = new byte[logoutMessage.length()];
final int resultSize = deflater.deflate(buffer);
final byte[] output = new byte[resultSize];
System.arraycopy(buffer, 0, output, 0, resultSize);
return Base64.encodeBase64String(output);
}
private String hash(byte[] hashBase, String algorithm) throws NoSuchAlgorithmException {
if ( hashBase == null ) { return null; }
final MessageDigest algo = MessageDigest.getInstance(algorithm);
final byte[] digest = algo.digest(hashBase);
return Base64.encodeBase64String(digest);
}
@Override
public String toBase64(byte[] bytes) {
return Base64.encodeBase64String(bytes);
}
private static void mvsInvoiceDemo() throws IOException {
//
// 1. 在ClientContextUtils类中, 配置好访问服务的基本信息,
// 然后,在此处生成对应的一个客户端连接对象
//
AisAccess service = new AisAccess(ClientContextUtils.getAuthInfo());
//
// 1.a 此处支持使用代理方式访问服务,用于不能直接访问华为云官网服务的情况, 例如,内网网络。
// 如果使用此处方式,需要同时在ClientContextUtils中,配置相应的代理服务器的参数类(ProxyHostInfo)
//
//AisAccess service = new AisAccessWithProxy(ClientContextUtils.getAuthInfo(), ClientContextUtils.getProxyHost());
try {
//
// 2.构建访问机动车购车发票识别服务需要的参数
//
String uri = "/v1.0/ocr/mvs-invoice";
byte[] fileData = FileUtils.readFileToByteArray(new File("data/mvs-invoice-demo.jpg"));
String fileBase64Str = Base64.encodeBase64String(fileData);
JSONObject json = new JSONObject();
json.put("image", fileBase64Str);
StringEntity stringEntity = new StringEntity(json.toJSONString(), "utf-8");
// 3.传入机动车购车发票识别服务对应的uri参数, 传入机动车购车发票识别服务需要的参数,
// 该参数主要通过JSON对象的方式传入, 使用POST方法调用服务
HttpResponse response = service.post(uri, stringEntity);
// 4.验证服务调用返回的状态是否成功,如果为200, 为成功, 否则失败。
ResponseProcessUtils.processResponseStatus(response);
// 5.处理服务返回的字符流。
ResponseProcessUtils.processResponse(response);
} catch (Exception e) {
e.printStackTrace();
} finally {
// 6.使用完毕,关闭服务的客户端连接
service.close();
}
}
/**
* This method trusts all SSL certificates exposed by the API.
*
* @param url
* @param username
* @param password
* @param httpMethod
* @param httpHeaders
* @param httpBody
* @return
* @throws Exception
*/
public static HTTPAPIResponse invokeHTTPAPI(String url, String username, String password, HTTPMethod httpMethod,
List<HTTPHeader> httpHeaders, String httpBody) throws Exception {
UrlValidator urlValidator = new UrlValidator(new String[] {"http", "https"}, UrlValidator.ALLOW_LOCAL_URLS);
if (!urlValidator.isValid(url)) {
throw new RuntimeException("Invalid URL");
}
// to allow special characters like whitespace in query parameters
String safeUrl = UrlEscapers.urlFragmentEscaper().escape(url);
// create HTTP request object and set body if applicable
HttpUriRequest httpRequest;
switch (httpMethod) {
case GET:
httpRequest = new HttpGet(safeUrl);
break;
case POST:
HttpPost httpPost = new HttpPost(safeUrl);
httpPost.setEntity(httpBody == null ? null : new StringEntity(httpBody, "UTF-8")); // StringEntity doesn't accept null string (exception is thrown)
httpRequest = httpPost;
break;
case PUT:
HttpPut httpPut = new HttpPut(safeUrl);
httpPut.setEntity(httpBody == null ? null : new StringEntity(httpBody, "UTF-8")); // StringEntity doesn't accept null string (exception is thrown)
httpRequest = httpPut;
break;
case DELETE:
httpRequest = new HttpDelete(safeUrl);
break;
default:
throw new IllegalArgumentException("Unrecognized HTTP method " + httpMethod);
}
// set request HTTP headers
for (HTTPHeader httpHeader : httpHeaders) {
httpRequest.setHeader(httpHeader.getName(), httpHeader.getValue());
}
// set HTTP basic auth
if (!"".equals(StringUtils.trimToEmpty(username))) {
String auth = username + ":" + password;
String encodedAuth = Base64.encodeBase64String(auth.getBytes());
String authHeader = "Basic " + encodedAuth;
httpRequest.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
}
final HTTPAPIResponse apiResponse = new HTTPAPIResponse();
ResponseHandler<Void> responseHandler = httpResponse -> {
apiResponse.setStatusCode(httpResponse.getStatusLine().getStatusCode());
apiResponse.getHttpHeaders().add(
new HTTPHeader("*Status-Line*", httpResponse.getStatusLine().toString()));
Header[] headers = httpResponse.getAllHeaders();
for (Header header: headers) {
apiResponse.getHttpHeaders().add(new HTTPHeader(header.getName(), header.getValue()));
}
HttpEntity entity = httpResponse.getEntity();
apiResponse.setHttpBody(entity != null ? EntityUtils.toString(entity) : null);
return null;
};
// build HTTP Client instance, trusting all SSL certificates, using system HTTP proxy if needed and exists
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial((TrustStrategy) (chain, authType) -> true).build();
HostnameVerifier allowAllHosts = new NoopHostnameVerifier();
SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext, allowAllHosts);
HttpClientBuilder httpClientBuilder = HttpClients.custom().setSSLSocketFactory(connectionFactory);
InetAddress urlHost = InetAddress.getByName(new URL(url).getHost());
if (!(urlHost.isLoopbackAddress() || urlHost.isSiteLocalAddress())) { // only use system proxy for external address
Proxy systemHTTPProxy = getSystemHTTPProxy();
if (systemHTTPProxy != null) {
InetSocketAddress addr = (InetSocketAddress) systemHTTPProxy.address();
httpClientBuilder.setProxy(new HttpHost(addr.getHostName(), addr.getPort()));
}
}
HttpClient httpClient = httpClientBuilder.build();
// invoke the API
try {
httpClient.execute(httpRequest, responseHandler);
} catch (ClientProtocolException e) {
throw new RuntimeException(e.getCause().getMessage(), e);
}
return apiResponse;
}
public static String encodeBase64String(byte[] data) {
return Base64.encodeBase64String(data);
}
/**
* encrypt a plain password
*
* @param aPlainPass a password in plain text
* @return an encrypted password
* @throws Exception
*/
public static String encryptPassword(@NotNull final String aPlainPass) throws Exception {
byte[] encBytes = encryptString(aPlainPass.getBytes(DEFAULT_CODEPAGE));
return Base64.encodeBase64String(encBytes);
}
/**
* Encrypt the Data with the secret key.
* **WARNING** Can only be decrypted by this class!!!
*
* @param data The data to encrypt.
* @return The encrypted, unreadable data.
* @throws Exception If something fails.
*/
public String encrypt(String data) throws Exception {
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] encrypted = cipher.doFinal(data.getBytes());
return Base64.encodeBase64String(encrypted);
}
/**
* 对二进制数据进行BASE64编码
*
* @param binaryData
* 二进制数据
* @return 编码后的字符串
*/
public static String Base64Encode(byte[] binaryData) {
String encodedstr = Base64.encodeBase64String(binaryData);
return encodedstr;
}
/**
* 签名
*
* @param data 签名内容
* @param algorithm 签名
* @param privateKey 签名私钥
* @return
* @throws Exception
*/
public static String signData(String data, String algorithm, RSAPrivateKey privateKey) throws Exception {
return Base64.encodeBase64String(signData(data.getBytes("UTF-8"), algorithm, privateKey));
}