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

The following examples show how to use org.apache.commons.codec.binary.Base64. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
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 2
Source Project: azure-libraries-for-java   Source File: TestKubernetesCluster.java    License: 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 Project: zstack   Source File: EncryptRSA.java    License: 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 4
Source Project: swellrt   Source File: WaveSignerFactory.java    License: 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 5
Source Project: pentaho-kettle   Source File: KettleDatabaseRepository.java    License: 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 6
Source Project: jmeter-plugins   Source File: Base64Encode.java    License: 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 7
Source Project: suro   Source File: TestNotice.java    License: 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 8
Source Project: spring-cloud-huawei   Source File: AuthHeaderStrategy.java    License: 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 9
Source Project: littleca   Source File: Sm2AuthApiController.java    License: 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 10
Source Project: SciGraph   Source File: BasicAuthFilter.java    License: 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 11
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 12
Source Project: elasticsearch-hadoop   Source File: EsApiKeyAuthScheme.java    License: 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 13
Source Project: java-client   Source File: ImagesComparisonTest.java    License: 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 14
Source Project: keycloak-extension-playground   Source File: CryptoUtil.java    License: 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 15
Source Project: java-study   Source File: AESUtil.java    License: 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 16
Source Project: herd   Source File: KmsDaoImpl.java    License: Apache License 2.0 6 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 17
Source Project: elasticsearch-hadoop   Source File: SpnegoNegotiator.java    License: 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 18
Source Project: httpclientAuthHelper   Source File: CustomNTLM2Engine.java    License: 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 19
/**
 * 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);
}
 
Example 20
@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;
}
 
Example 21
Source Project: elasticsearch-hadoop   Source File: AutoElasticsearch.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 22
Source Project: snowflake-jdbc   Source File: SFTrustManager.java    License: Apache License 2.0 5 votes vote down vote up
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;
  }
}
 
Example 23
Source Project: cosmic   Source File: ConsoleProxyPasswordBasedEncryptor.java    License: Apache License 2.0 5 votes vote down vote up
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;
    }
}
 
Example 24
Source Project: deeplearning4j   Source File: WordVectorSerializer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 25
Source Project: cloudstack   Source File: VMInstanceVO.java    License: Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example 26
Source Project: scipio-erp   Source File: Main.java    License: Apache License 2.0 5 votes vote down vote up
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()));
    }
}
 
Example 27
Source Project: cloudstack   Source File: UserCloudAPIExecutor.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 28
Source Project: dbys   Source File: DynamicKey5.java    License: GNU General Public License v3.0 5 votes vote down vote up
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;
}
 
Example 29
Source Project: birt   Source File: BasicComponent.java    License: Eclipse Public License 1.0 5 votes vote down vote up
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 + "--" );
}
 
Example 30
Source Project: rice   Source File: EncryptionService.java    License: Educational Community License v2.0 5 votes vote down vote up
/**
 * 
 * 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));
}