下面列出了org.apache.http.client.methods.HttpTrace#org.apache.commons.codec.binary.Base64 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private SecretModel getBallerinaConfSecret(String configFilePath, String serviceName) throws
KubernetesPluginException {
//create a new config map model with ballerina conf
SecretModel secretModel = new SecretModel();
secretModel.setName(getValidName(serviceName) + "-ballerina-conf" + SECRET_POSTFIX);
secretModel.setMountPath(BALLERINA_CONF_MOUNT_PATH);
Path dataFilePath = Paths.get(configFilePath);
if (!dataFilePath.isAbsolute()) {
dataFilePath = KubernetesContext.getInstance().getDataHolder().getSourceRoot().resolve(dataFilePath)
.normalize();
}
String content = Base64.encodeBase64String(KubernetesUtils.readFileContent(dataFilePath));
Map<String, String> dataMap = new HashMap<>();
dataMap.put(BALLERINA_CONF_FILE_NAME, content);
secretModel.setData(dataMap);
secretModel.setBallerinaConf(configFilePath);
secretModel.setReadOnly(false);
return secretModel;
}
private String getSshKey() throws Exception {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
KeyPair keyPair=keyPairGenerator.generateKeyPair();
RSAPublicKey publicKey=(RSAPublicKey)keyPair.getPublic();
ByteArrayOutputStream byteOs = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(byteOs);
dos.writeInt("ssh-rsa".getBytes().length);
dos.write("ssh-rsa".getBytes());
dos.writeInt(publicKey.getPublicExponent().toByteArray().length);
dos.write(publicKey.getPublicExponent().toByteArray());
dos.writeInt(publicKey.getModulus().toByteArray().length);
dos.write(publicKey.getModulus().toByteArray());
String publicKeyEncoded = new String(
Base64.encodeBase64(byteOs.toByteArray()));
return "ssh-rsa " + publicKeyEncoded + " ";
}
public Object decrypt1(String password) throws Exception{
initKey();
try {
byte[] srcBytes = encodeUTF8(password);
byte[] desBytes = decrypt(Base64.decodeBase64(srcBytes), key2);
String tempdecodeUTF8 = decodeUTF8(desBytes);
if (tempdecodeUTF8.substring(0, appendString.length()).equals(appendString)){
return tempdecodeUTF8.substring(appendString.length(),tempdecodeUTF8.length());
}
return password;
}catch (Exception e){
logger.debug(e.getMessage());
return password;
}
}
private byte[] readBase64Bytes(InputStream stream) throws IOException {
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line;
while ((line = reader.readLine()) != null) {
line = line.trim();
// read past ----BEGIN PRIVATE KEY and ----END PRIVATE KEY lines
if (line.startsWith("-----BEGIN") || line.startsWith("-----END")) {
continue;
}
builder.append(line);
}
return Base64.decodeBase64(builder.toString().getBytes());
}
/**
* GZips and then base64 encodes an array of bytes to a String
*
* @param val
* the array of bytes to convert to a string
* @return the base64 encoded string
* @throws IOException
* in the case there is a Base64 or GZip encoding problem
*/
public static final String byteArrayToString( byte[] val ) throws IOException {
String string;
if ( val == null ) {
string = null;
} else {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzos = new GZIPOutputStream( baos );
BufferedOutputStream bos = new BufferedOutputStream( gzos );
bos.write( val );
bos.flush();
bos.close();
string = new String( Base64.encodeBase64( baos.toByteArray() ) );
}
return string;
}
@Override
public synchronized String execute(SampleResult previousResult, Sampler currentSampler)
throws InvalidVariableException {
String sourceString = values[0].execute();
String decodedValue = new String(Base64.encodeBase64(sourceString.getBytes()));
if (values.length > 1) {
String variableName = values[1].execute();
if (variableName.length() > 0) {// Allow for empty name
final JMeterVariables variables = getVariables();
if (variables != null) {
variables.put(variableName, decodedValue);
}
}
}
return decodedValue;
}
@Test
public void testSQSBase64() throws IOException {
String desc = "{\n" +
" \"type\": \"sqs\",\n" +
" \"queues\": [\n" +
" \"queue1\"\n" +
" ],\n" +
" \"enableBase64Encoding\": true,\n" +
" \"region\": \"us-east-1\",\n" +
" \"connectionTimeout\": 3000,\n" +
" \"maxConnections\": 3,\n" +
" \"socketTimeout\": 1000,\n" +
" \"maxRetries\": 3\n" +
"}";
SqsTest sqsTest = new SqsTest(desc).invoke();
ArgumentCaptor<SendMessageRequest> captor = sqsTest.getCaptor();
Notice queueNotice = sqsTest.getQueueNotice();
assertEquals(captor.getValue().getMessageBody(), new String(Base64.encodeBase64("message".getBytes()),
Charsets.UTF_8));
assertEquals(captor.getValue().getQueueUrl(), "queueURL");
assertEquals(queueNotice.recv(), new String(Base64.decodeBase64("receivedMessage".getBytes()), Charsets.UTF_8));
}
protected void decode(JsonNode authNode) throws IOException {
if (authNode == null) {
return;
}
Map<String, String> authHeaders = new HashMap<String, String>();
String authStr = authNode.asText();
String authBase64Decode = new String(Base64.decodeBase64(authStr), "UTF-8");
String[] auths = authBase64Decode.split("@");
String[] akAndShaAkSk = auths[1].split(":");
if (auths.length != EXPECTED_ARR_LENGTH || akAndShaAkSk.length != EXPECTED_ARR_LENGTH) {
LOGGER.error("get docker config failed. The data is not valid cause of unexpected format");
return;
}
String project = auths[0];
String ak = akAndShaAkSk[0];
String shaAkSk = akAndShaAkSk[1];
authHeaders.put("X-Service-AK", ak);
authHeaders.put("X-Service-ShaAKSK", shaAkSk);
authHeaders.put("X-Service-Project", project);
defaultAuthHeaders = authHeaders;
loaded = true;
}
@PostMapping("refresh")
@ResponseBody
public Result authRefresh(@RequestBody EncodeRequestDTO authRequestEncode, HttpServletRequest request) throws Exception {
String encodeData = authRequestEncode.getData();
if (StrUtil.isEmpty(encodeData)) {
throw new AuthException("参数为空");
}
AuthProperties.Sm2AuthProperties sm2Config = authProperties.getSm2();
String data = null;
try {
data = new String(sm2.decrypt(Base64.decodeBase64(encodeData), sm2Config.getServerPrivateKey()), "UTF-8");
} catch (Exception e) {
log.error("认证服务解密异常:[{}],加密数据:[{}]", e, encodeData);
throw new AuthException("认证服务解密异常");
}
AuthRefreshRequestDTO authRefreshRequestDTO = JSONUtil.parseObject(data, AuthRefreshRequestDTO.class);
AuthResultWrapper resultWrapper = apiAccountAuthHelper.authRefresh(authRefreshRequestDTO, AuthType.SM2, request);
return encodeResult(resultWrapper, sm2Config);
}
@Override
public String getHeader(String name) {
if (HttpHeaders.AUTHORIZATION.equals(name)) {
String authKey = null;
if (!isNullOrEmpty(getRequest().getParameter(keyParam))) {
authKey = format("%1$s:%1$s", getRequest().getParameter(keyParam));
} else if (defaultApiKey.isPresent()) {
authKey = format("%1$s:%1$s", defaultApiKey.get());
} else {
return null;
}
return format("Basic %s", Base64.encodeBase64String(authKey.getBytes()));
} else {
return super.getHeader(name);
}
}
public static void main(String[] args) throws Exception {
MessageDigest md = MessageDigest.getInstance(MessageDigestAlgorithms.MD5);
md.update("texto a cifrar".getBytes());
byte[] digest = md.digest();
// Se escribe byte a byte en hexadecimal
for (byte b : digest) {
System.out.print(Integer.toHexString(0xFF & b));
}
System.out.println();
// Se escribe codificado base 64. Se necesita la librer�a
// commons-codec-x.x.x.jar de Apache
byte[] encoded = Base64.encodeBase64(digest);
System.out.println(new String(encoded));
}
/**
* Implementation method for authentication
*/
private String authenticate(Credentials credentials) throws AuthenticationException {
if (!(credentials instanceof EsApiKeyCredentials)) {
throw new AuthenticationException("Incorrect credentials type provided. Expected [" + EsApiKeyCredentials.class.getName()
+ "] but got [" + credentials.getClass().getName() + "]");
}
EsApiKeyCredentials esApiKeyCredentials = ((EsApiKeyCredentials) credentials);
String authString = null;
if (esApiKeyCredentials.getToken() != null && StringUtils.hasText(esApiKeyCredentials.getToken().getName())) {
EsToken token = esApiKeyCredentials.getToken();
String keyComponents = token.getId() + ":" + token.getApiKey();
byte[] base64Encoded = Base64.encodeBase64(keyComponents.getBytes(StringUtils.UTF_8));
String tokenText = new String(base64Encoded, StringUtils.UTF_8);
authString = EsHadoopAuthPolicies.APIKEY + " " + tokenText;
}
return authString;
}
@Test
public void verifyFeaturesMatching() {
byte[] screenshot = Base64.encodeBase64(driver.getScreenshotAs(OutputType.BYTES));
FeaturesMatchingResult result = driver
.matchImagesFeatures(screenshot, screenshot, new FeaturesMatchingOptions()
.withDetectorName(FeatureDetector.ORB)
.withGoodMatchesFactor(40)
.withMatchFunc(MatchingFunction.BRUTE_FORCE_HAMMING)
.withEnabledVisualization());
assertThat(result.getVisualization().length, is(greaterThan(0)));
assertThat(result.getCount(), is(greaterThan(0)));
assertThat(result.getTotalCount(), is(greaterThan(0)));
assertFalse(result.getPoints1().isEmpty());
assertNotNull(result.getRect1());
assertFalse(result.getPoints2().isEmpty());
assertNotNull(result.getRect2());
}
public static String encrypt(String payload, String key) {
try {
byte[] keyBytes = sha256(key);
byte[] ivBytes = Arrays.copyOf(keyBytes, 16);
Cipher cipher = Cipher.getInstance(ALG_TRANSFORMATION);
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(keyBytes, ALG), new IvParameterSpec(ivBytes));
byte[] encrypted = cipher.doFinal(payload.getBytes(StandardCharsets.UTF_8));
return Base64.encodeBase64URLSafeString(encrypted);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
/**
* AES 解密操作
* @param content
* @param password
* @return
*/
public static String decrypt(String content, String password) {
try {
//实例化
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
//使用密钥初始化,设置为解密模式
cipher.init(Cipher.DECRYPT_MODE, getSecretKey(password));
//执行操作
byte[] result = cipher.doFinal(Base64.decodeBase64(content));
return new String(result, "utf-8");
} catch (Exception ex) {
Logger.getLogger(AESUtil.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
@Override
public String decrypt(AwsParamsDto awsParamsDto, String base64ciphertextBlob)
{
// Construct a new AWS KMS service client using the specified client configuration.
// A credentials provider chain will be used that searches for credentials in this order:
// - Environment Variables - AWS_ACCESS_KEY_ID and AWS_SECRET_KEY
// - Java System Properties - aws.accessKeyId and aws.secretKey
// - Instance Profile Credentials - delivered through the Amazon EC2 metadata service
AWSKMSClient awsKmsClient = new AWSKMSClient(awsHelper.getClientConfiguration(awsParamsDto));
// Decode the base64 encoded ciphertext.
ByteBuffer ciphertextBlob = ByteBuffer.wrap(Base64.decodeBase64(base64ciphertextBlob));
// Create the decrypt request.
DecryptRequest decryptRequest = new DecryptRequest().withCiphertextBlob(ciphertextBlob);
// Call AWS KMS decrypt service method.
DecryptResult decryptResult = kmsOperations.decrypt(awsKmsClient, decryptRequest);
// Get decrypted plaintext data.
ByteBuffer plainText = decryptResult.getPlaintext();
// Return the plain text as a string.
return new String(plainText.array(), StandardCharsets.UTF_8);
}
public String send() throws GSSException {
byte[] sendData;
if (gssContext == null) {
Assert.isTrue(token == null, "GSS Context not yet initialized. Client must be the initiator.");
gssContext = gssManager.createContext(servicePrincipalName, spnegoOID, userCredential, GSSCredential.DEFAULT_LIFETIME);
sendData = gssContext.initSecContext(new byte[0], 0, 0);
} else if (token != null) {
sendData = gssContext.initSecContext(token, 0, token.length);
token = null;
} else {
throw new EsHadoopTransportException("Missing required negotiation token");
}
if (sendData == null) {
return null;
} else {
return new String(Base64.encodeBase64(sendData), StringUtils.UTF_8);
}
}
/** Constructor to use when message contents are known */
NTLMMessage(String messageBody, int expectedType) throws AuthenticationException {
messageContents = Base64.decodeBase64(EncodingUtils.getBytes(messageBody,
DEFAULT_CHARSET));
// Look for NTLM message
if (messageContents.length < SIGNATURE.length) {
throw new AuthenticationException("NTLM message decoding error - packet too short");
}
int i = 0;
while (i < SIGNATURE.length) {
if (messageContents[i] != SIGNATURE[i]) {
throw new AuthenticationException(
"NTLM message expected - instead got unrecognized bytes");
}
i++;
}
// Check to be sure there's a type 2 message indicator next
int type = readULong(SIGNATURE.length);
if (type != expectedType) {
throw new AuthenticationException("NTLM type " + Integer.toString(expectedType)
+ " message expected - instead got type " + Integer.toString(type));
}
currentOutputPosition = messageContents.length;
}
/**
* Generates secure random bytes of the given length and return base 64 encoded bytes as url safe String. This is not the length of the
* resulting string!
* @param numberOfBytes
* @return
*/
public static String getSecureRandomUrlSaveString(final int numberOfBytes)
{
final SecureRandom random = new SecureRandom();
final byte[] bytes = new byte[numberOfBytes];
random.nextBytes(bytes);
return Base64.encodeBase64URLSafeString(bytes);
}
@Override
public int read(byte[] b) throws IOException {
int numRead = super.read(b);
if (numRead > 0) {
byte[] copy = b;
if (numRead < b.length) {
// isBase64 checks the whole length of byte[], we need to limit it to numRead
copy = Arrays.copyOf(b, numRead);
}
if (!Base64.isBase64(copy)) {
throw new IOException("Data is not base64 encoded.");
}
}
return numRead;
}
private EsToken getCred(String key, Map<String, String> credentials) {
EsToken token = null;
String serializedToken = credentials.get(key);
if (serializedToken != null && !serializedToken.equals("placeholder")) {
byte[] rawData = Base64.decodeBase64(serializedToken);
try {
token = new EsToken(new DataInputStream(new FastByteArrayInputStream(rawData)));
} catch (IOException e) {
throw new EsHadoopException("Could not deserialize EsToken", e);
}
}
return token;
}
private OCSPResp b64ToOCSPResp(String ocspRespB64)
{
try
{
return new OCSPResp(Base64.decodeBase64(ocspRespB64));
}
catch (Throwable ex)
{
LOGGER.debug("Could not cover OCSP Response from Base64 to OCSPResp object");
return null;
}
}
public String decryptText(final String encryptedText) {
if (encryptedText == null || encryptedText.isEmpty()) {
return encryptedText;
}
try {
final byte[] encryptedBytes = Base64.decodeBase64(encryptedText);
byte[] iv = Arrays.copyOf(encryptedBytes, this.keyIvPair.getIvSize());
int maclength = hmacLength(this.authenticationKey);
byte[] hmac1 = Arrays.copyOfRange(encryptedBytes, encryptedBytes.length - maclength, encryptedBytes.length);
byte[] ciphertext = Arrays.copyOfRange(encryptedBytes, this.keyIvPair.getIvSize(), encryptedBytes.length - maclength);
byte[] data = concat(iv, ciphertext);
byte[] hmac2 = generateHMAC(this.authenticationKey, data);
if (!Arrays.equals(hmac1, hmac2)) {
s_logger.error("Incorrect HMAC");
return null;
}
final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
final SecretKeySpec keySpec = new SecretKeySpec(this.keyIvPair.getKeyBytes(), "AES");
cipher.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(this.keyIvPair.getIvBytes()));
return new String(cipher.doFinal(ciphertext));
} catch (Exception e) {
s_logger.error("Unexpected exception ", e);
return null;
}
}
/**
* This utility method serializes ElementPair into JSON + packs it into Base64-encoded string
*
* @return
*/
protected String toEncodedJson() {
ObjectMapper mapper = SequenceElement.mapper();
Base64 base64 = new Base64(Integer.MAX_VALUE);
try {
String json = mapper.writeValueAsString(this);
String output = base64.encodeAsString(json.getBytes("UTF-8"));
return output;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public VMInstanceVO(long id, long serviceOfferingId, String name, String instanceName, Type type, Long vmTemplateId, HypervisorType hypervisorType, long guestOSId,
long domainId, long accountId, long userId, boolean haEnabled) {
this.id = id;
hostName = name != null ? name : uuid;
if (vmTemplateId != null) {
templateId = vmTemplateId;
}
this.instanceName = instanceName;
this.type = type;
this.guestOSId = guestOSId;
this.haEnabled = haEnabled;
state = State.Stopped;
this.accountId = accountId;
this.domainId = domainId;
this.serviceOfferingId = serviceOfferingId;
this.hypervisorType = hypervisorType;
this.userId = userId;
limitCpuUse = false;
try {
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
byte[] randomBytes = new byte[16];
random.nextBytes(randomBytes);
vncPassword = Base64.encodeBase64URLSafeString(randomBytes);
} catch (NoSuchAlgorithmException e) {
s_logger.error("Unexpected exception in SecureRandom Algorithm selection ", e);
}
}
public static void main(String[] args) throws Exception {
if ("-crypt".equals(args[0])) {
System.out.println(HashCrypt.cryptUTF8(args[1], null, args[2]));
} else if ("-digest".equals(args[0])) {
String digest = HashCrypt.digestHash("SHA", null, args[1]);
System.out.println(digest);
} else if ("-kek".equals(args[0])) {
AesCipherService cs = new AesCipherService();
System.out.println(Base64.encodeBase64String(cs.generateNewKey().getEncoded()));
// SCIPIO: 2018-09-07: DISABLED generating new DES keys - DES is insecure
// and the DES code in Scipio should only be used to decrypt existing records.
//} else if ("-kek-old".equals(args[0])) {
// System.out.println(Base64.encodeBase64String(DesCrypt.generateKey().getEncoded()));
}
}
/**
* 1. Signs a string with a secret key using SHA-1 2. Base64 encode the result 3. URL encode the final result
*
* @param request
* @param key
* @return
*/
public static String signRequest(String request, String key) {
try {
Mac mac = Mac.getInstance("HmacSHA1");
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "HmacSHA1");
mac.init(keySpec);
mac.update(request.getBytes());
byte[] encryptedBytes = mac.doFinal();
return URLEncoder.encode(Base64.encodeBase64String(encryptedBytes), "UTF-8");
} catch (Exception ex) {
System.out.println(ex);
}
return null;
}
public static String generateDynamicKey(String appID, String appCertificate, String channel, int ts, int salt, long uid, int expiredTs, TreeMap<Short, String> extra, short service) throws Exception {
String signature = generateSignature(appCertificate, service, appID, ts, salt, channel, uid, expiredTs, extra);
DynamicKey5Content content = new DynamicKey5Content(service, signature, new Hex().decode(appID.getBytes()), ts, salt, expiredTs, extra);
byte[] bytes = pack(content);
byte[] encoded = new Base64().encode(bytes);
String base64 = new String(encoded);
return version + base64;
}
private void writeImages( )
{
for ( String uri : imageSrc )
{
String imageType = uri.substring( uri.indexOf( '.' ) + 1 );
mhtPartWriter.println( );
mhtPartWriter.println( "--" + BOUNDARY );
mhtPartWriter.println( "Content-Type: image/" + imageType );
mhtPartWriter.println( "Content-Transfer-Encoding: base64" );
mhtPartWriter.println( "Content-Location:" + uri );
mhtPartWriter.println( );
try
{
byte[] data = EmitterUtil.getImageData( uri );
if ( data != null && data.length != 0 )
{
Base64 base = new Base64( );
String pic2Text = new String( base.encode( data ) );
mhtPartWriter.println( pic2Text );
}
}
catch ( IOException e )
{
logger.log( Level.WARNING, e.getLocalizedMessage( ) );
}
}
mhtPartWriter.println( );
mhtPartWriter.println( "--" + BOUNDARY + "--" );
}
/**
*
* This method generates keys. This method is implementation specific and should not be present in any general purpose interface
* extracted from this class.
*
* @return
* @throws Exception
*/
public static String generateEncodedKey() throws Exception {
KeyGenerator keygen = KeyGenerator.getInstance("DES");
SecretKey desKey = keygen.generateKey();
// Create the cipher
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init((Cipher.WRAP_MODE), desKey);
SecretKeyFactory desFactory = SecretKeyFactory.getInstance("DES");
DESKeySpec desSpec = (DESKeySpec) desFactory.getKeySpec(desKey, javax.crypto.spec.DESKeySpec.class);
byte[] rawDesKey = desSpec.getKey();
return new String(Base64.encodeBase64(rawDesKey));
}