org.apache.commons.codec.binary.Base64 Java Examples

The following examples show how to use org.apache.commons.codec.binary.Base64. 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: AuthHeaderStrategy.java    From spring-cloud-huawei with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #2
Source File: TestKubernetesCluster.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
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 + " ";
}
 
Example #3
Source File: CryptoUtil.java    From keycloak-extension-playground with Apache License 2.0 6 votes vote down vote up
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;
    }
 
Example #4
Source File: AESUtil.java    From java-study with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #5
Source File: ImagesComparisonTest.java    From java-client with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #6
Source File: EncryptRSA.java    From zstack with Apache License 2.0 6 votes vote down vote up
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;
	}

}
 
Example #7
Source File: EsApiKeyAuthScheme.java    From elasticsearch-hadoop with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #8
Source File: MD5Example.java    From chuidiang-ejemplos with GNU Lesser General Public License v3.0 6 votes vote down vote up
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));
   }
 
Example #9
Source File: WaveSignerFactory.java    From swellrt with Apache License 2.0 6 votes vote down vote up
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());
}
 
Example #10
Source File: KettleDatabaseRepository.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #11
Source File: Sm2AuthApiController.java    From littleca with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #12
Source File: BasicAuthFilter.java    From SciGraph with Apache License 2.0 6 votes vote down vote up
@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);
  }
}
 
Example #13
Source File: Base64Encode.java    From jmeter-plugins with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #14
Source File: SpnegoNegotiator.java    From elasticsearch-hadoop with Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example #15
Source File: TestNotice.java    From suro with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #16
Source File: SecretAnnotationProcessor.java    From module-ballerina-kubernetes with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #17
Source File: CustomNTLM2Engine.java    From httpclientAuthHelper with Apache License 2.0 6 votes vote down vote up
/** 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;
}
 
Example #18
Source File: CipherUtil.java    From molicode with Apache License 2.0 5 votes vote down vote up
/**
 * 随机生成密钥对
 *
 * @throws NoSuchAlgorithmException
 */
public static Pair<String, String> genKeyPair(int size) throws NoSuchAlgorithmException {
    // KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
    KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
    // 初始化密钥对生成器,密钥大小为512-1024位
    keyPairGen.initialize(size, new SecureRandom());
    // 生成一个密钥对,保存在keyPair中
    KeyPair keyPair = keyPairGen.generateKeyPair();
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();   // 得到私钥
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();  // 得到公钥
    String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded()));
    // 得到私钥字符串
    String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded())));
    return Pair.of(publicKeyString, privateKeyString);
}
 
Example #19
Source File: WebPage.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
public File getRecording(String fileName) throws IOException {
  browser.executeScript("kurentoTest.recordingToData();");
  String recording = getProperty("recordingData").toString();

  // Base64 to File
  File outputFile = new File(fileName);
  byte[] bytes = Base64.decodeBase64(recording.substring(recording.lastIndexOf(",") + 1));
  FileUtils.writeByteArrayToFile(outputFile, bytes);

  return outputFile;
}
 
Example #20
Source File: EncryptionUtil.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public static String generateSignature(String data, String key) {
    try {
        final Mac mac = Mac.getInstance("HmacSHA1");
        final SecretKeySpec keySpec = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA1");
        mac.init(keySpec);
        mac.update(data.getBytes("UTF-8"));
        final byte[] encryptedBytes = mac.doFinal();
        return Base64.encodeBase64String(encryptedBytes);
    } catch (NoSuchAlgorithmException | InvalidKeyException | UnsupportedEncodingException e) {
        s_logger.error("exception occurred which encoding the data." + e.getMessage());
        throw new CloudRuntimeException("unable to generate signature", e);
    }
}
 
Example #21
Source File: KmsDaoImpl.java    From herd with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #22
Source File: XMLHandler.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
public static String encodeBinaryData( byte[] val ) throws IOException {
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  GZIPOutputStream gzos = new GZIPOutputStream( baos );
  BufferedOutputStream bos = new BufferedOutputStream( gzos );
  bos.write( val );
  bos.flush();
  bos.close();

  return new String( Base64.encodeBase64( baos.toByteArray() ) );
}
 
Example #23
Source File: EncryptUriProcessor.java    From knox with Apache License 2.0 5 votes vote down vote up
private String encode( String string ) throws UnsupportedEncodingException {
  EncryptionResult result = cryptoService.encryptForCluster(clusterName,
      EncryptUriDescriptor.PASSWORD_ALIAS,
      string.getBytes(StandardCharsets.UTF_8));
  string = Base64.encodeBase64URLSafeString(result.toByteAray());
  return string;
}
 
Example #24
Source File: ExtensionInterfaceBeanTest.java    From development with Apache License 2.0 5 votes vote down vote up
private ExtensionInterfaceBean getTestBean(String instanceId,
        String subscriptionId, String organizationId) throws Exception {
    instanceAccess = Mockito.mock(InstanceAccess.class);

    serverInfo = getServerInfoMock(3);

    String encodedInstId = Base64.encodeBase64URLSafeString(
            instanceId.getBytes(StandardCharsets.UTF_8));
    String encodedSubId = Base64.encodeBase64URLSafeString(
            subscriptionId.getBytes(StandardCharsets.UTF_8));
    String encodedOrgId = Base64.encodeBase64URLSafeString(
            organizationId.getBytes(StandardCharsets.UTF_8));

    Mockito.when(instanceAccess.getAccessInfo(instanceID, subscriptionID,
            organizationID)).thenReturn("Access info from IaaS");
    Mockito.<List<? extends ServerInformation>> when(instanceAccess
            .getServerDetails(instanceID, subscriptionID, organizationID))
            .thenReturn(serverInfo);

    ExtensionInterfaceBean bean = new ExtensionInterfaceBean();
    bean.setInstanceId(encodedInstId);
    bean.setSubscriptionId(encodedSubId);
    bean.setOrganizationId(encodedOrgId);
    bean.setInstanceAccess(instanceAccess);

    return bean;
}
 
Example #25
Source File: PortalAction.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
public void test() throws Exception {
	try (FileInputStream in = new FileInputStream(new File("d:/a.png"));
			ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
		BufferedImage image = ImageIO.read(in);
		ImageIO.write(image, "png", baos);
		String icon = Base64.encodeBase64String(baos.toByteArray());
	}
}
 
Example #26
Source File: EncryptionObject.java    From x7 with Apache License 2.0 5 votes vote down vote up
public T getObj() {
	if (Objects.isNull(obj) && !Objects.isNull(text)){
		byte[] bytes = Base64.decodeBase64(text);
		try {
			String json = new String(bytes,"UTF-8");
			obj = (T) JsonX.toObject(json, clz);
			return obj;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}
	}
	return obj;
}
 
Example #27
Source File: SelfSignUpUtil.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * This method is used to set the Authorization header for the request sent to consent management service
 *
 * @param httpMethod   The method which requires to add the Authorization header
 * @param tenantDomain The tenant domain
 * @throws APIManagementException APIManagement Exception
 */
private static void setAuthorizationHeader(HttpRequestBase httpMethod, String tenantDomain)
        throws APIManagementException {
    UserRegistrationConfigDTO signupConfig = SelfSignUpUtil.getSignupConfiguration(tenantDomain);
    String adminUsername = signupConfig.getAdminUserName();
    String adminPassword = signupConfig.getAdminPassword();
    String toEncode = adminUsername + ":" + adminPassword;
    byte[] encoding = Base64.encodeBase64(toEncode.getBytes());
    String authHeader = new String(encoding, Charset.defaultCharset());
    httpMethod.addHeader(HTTPConstants.HEADER_AUTHORIZATION,
            APIConstants.AUTHORIZATION_HEADER_BASIC + " " + authHeader);
}
 
Example #28
Source File: CryptoServiceImpl.java    From paymentgateway with GNU General Public License v3.0 5 votes vote down vote up
protected boolean verify(PublicKey key, String plainData, String signature) throws MipsException {
	try {
		byte[] sign = Base64.decodeBase64(signature);
		Signature instance = Signature.getInstance("SHA256withRSA");
		instance.initVerify(key);
		instance.update(plainData.getBytes("UTF-8"));
		return instance.verify(sign); 
	}
	catch (Exception e) {
		throw new MipsException(RespCode.INTERNAL_ERROR, "verify failed: ", e);
	}
}
 
Example #29
Source File: EnhancedKeyVaultTest.java    From azure-keyvault-java with MIT License 5 votes vote down vote up
private HttpMessageSecurity getMessageSecurityWithKeys() throws Exception{
    return new HttpMessageSecurity("Token",
                                   new String(Base64.decodeBase64(clientEncryptionKeyBase64)),
                                   new String(Base64.decodeBase64(clientSignatureKeyBase64)),
                                   new String(Base64.decodeBase64(serverEncryptionKeyBase64)),
                                   new String(Base64.decodeBase64(serverSignatureKeyBase64)),
                                   true);
}
 
Example #30
Source File: Base64Encoder.java    From nem.core with MIT License 5 votes vote down vote up
/**
 * Converts a string to a byte array.
 *
 * @param base64String The input Base64 string.
 * @return The output byte array.
 */
public static byte[] getBytes(final String base64String) {
	final Base64 codec = new Base64();
	final byte[] encodedBytes = StringEncoder.getBytes(base64String);
	if (!codec.isInAlphabet(encodedBytes, true)) {
		throw new IllegalArgumentException("malformed base64 string passed to getBytes");
	}

	return codec.decode(encodedBytes);
}