Search in sources :

Example 96 with Base64.encodeBase64String

use of org.apache.commons.codec.binary.Base64.encodeBase64String in project wso2-synapse by wso2.

the class PKCS8KeyStoreLoader method createPrivateKey.

/**
 * Takes the (unencrypted) RSA private key in pkcs8 format, and creates a private key out of it
 *
 * @param keyBytes Byte Array of the private key
 * @return PKCS8Encoded PrivateKey
 */
private PrivateKey createPrivateKey(byte[] keyBytes) {
    int dataStart = HEADER.length();
    int dataEnd = keyBytes.length - FOOTER.length() - 1;
    int dataLength = dataEnd - dataStart;
    byte[] keyContent = new byte[dataLength];
    System.arraycopy(keyBytes, dataStart, keyContent, 0, dataLength);
    PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(new Base64().decode(keyContent));
    try {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePrivate(pkcs8EncodedKeySpec);
    } catch (NoSuchAlgorithmException e) {
        handleException("Error getting a KeyFactory instance", e);
    } catch (InvalidKeySpecException e) {
        handleException("Error generating a private key", e);
    }
    return null;
}
Also used : Base64(org.apache.commons.codec.binary.Base64) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) InvalidKeySpecException(java.security.spec.InvalidKeySpecException)

Example 97 with Base64.encodeBase64String

use of org.apache.commons.codec.binary.Base64.encodeBase64String in project hadoop by apache.

the class RMWebServices method createContainerLaunchContext.

/**
   * Create the ContainerLaunchContext required for the
   * ApplicationSubmissionContext. This function takes the user information and
   * generates the ByteBuffer structures required by the ContainerLaunchContext
   * 
   * @param newApp
   *          the information provided by the user
   * @return created context
   * @throws BadRequestException
   * @throws IOException
   */
protected ContainerLaunchContext createContainerLaunchContext(ApplicationSubmissionContextInfo newApp) throws BadRequestException, IOException {
    // create container launch context
    HashMap<String, ByteBuffer> hmap = new HashMap<String, ByteBuffer>();
    for (Map.Entry<String, String> entry : newApp.getContainerLaunchContextInfo().getAuxillaryServiceData().entrySet()) {
        if (entry.getValue().isEmpty() == false) {
            Base64 decoder = new Base64(0, null, true);
            byte[] data = decoder.decode(entry.getValue());
            hmap.put(entry.getKey(), ByteBuffer.wrap(data));
        }
    }
    HashMap<String, LocalResource> hlr = new HashMap<String, LocalResource>();
    for (Map.Entry<String, LocalResourceInfo> entry : newApp.getContainerLaunchContextInfo().getResources().entrySet()) {
        LocalResourceInfo l = entry.getValue();
        LocalResource lr = LocalResource.newInstance(URL.fromURI(l.getUrl()), l.getType(), l.getVisibility(), l.getSize(), l.getTimestamp());
        hlr.put(entry.getKey(), lr);
    }
    DataOutputBuffer out = new DataOutputBuffer();
    Credentials cs = createCredentials(newApp.getContainerLaunchContextInfo().getCredentials());
    cs.writeTokenStorageToStream(out);
    ByteBuffer tokens = ByteBuffer.wrap(out.getData());
    ContainerLaunchContext ctx = ContainerLaunchContext.newInstance(hlr, newApp.getContainerLaunchContextInfo().getEnvironment(), newApp.getContainerLaunchContextInfo().getCommands(), hmap, tokens, newApp.getContainerLaunchContextInfo().getAcls());
    return ctx;
}
Also used : Base64(org.apache.commons.codec.binary.Base64) HashMap(java.util.HashMap) ContainerLaunchContext(org.apache.hadoop.yarn.api.records.ContainerLaunchContext) ByteBuffer(java.nio.ByteBuffer) LocalResource(org.apache.hadoop.yarn.api.records.LocalResource) LocalResourceInfo(org.apache.hadoop.yarn.server.resourcemanager.webapp.dao.LocalResourceInfo) DataOutputBuffer(org.apache.hadoop.io.DataOutputBuffer) Map(java.util.Map) HashMap(java.util.HashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) Credentials(org.apache.hadoop.security.Credentials)

Example 98 with Base64.encodeBase64String

use of org.apache.commons.codec.binary.Base64.encodeBase64String in project amos-ss17-alexa by c-i-ber.

the class SignedRequestsHelper method hmac.

/**
 * Compute the HMAC.
 *
 * @param stringToSign  String to compute the HMAC over.
 * @return              base64-encoded hmac value.
 */
private String hmac(String stringToSign) {
    String signature = null;
    byte[] data;
    byte[] rawHmac;
    try {
        data = stringToSign.getBytes(UTF8_CHARSET);
        rawHmac = mac.doFinal(data);
        Base64 encoder = new Base64();
        signature = new String(encoder.encode(rawHmac));
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(UTF8_CHARSET + " is unsupported!", e);
    }
    return signature;
}
Also used : Base64(org.apache.commons.codec.binary.Base64) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 99 with Base64.encodeBase64String

use of org.apache.commons.codec.binary.Base64.encodeBase64String in project leopard by tanhaichao.

the class tls_sigature method CheckTLSSignatureEx.

public static CheckTLSSignatureResult CheckTLSSignatureEx(String urlSig, long sdkAppid, String identifier, String publicKey) throws DataFormatException {
    CheckTLSSignatureResult result = new CheckTLSSignatureResult();
    Security.addProvider(new BouncyCastleProvider());
    // DeBaseUrl64 urlSig to json
    Base64 decoder = new Base64();
    byte[] compressBytes = base64_url.base64DecodeUrl(urlSig.getBytes(Charset.forName("UTF-8")));
    // Decompression
    Inflater decompression = new Inflater();
    decompression.setInput(compressBytes, 0, compressBytes.length);
    byte[] decompressBytes = new byte[1024];
    int decompressLength = decompression.inflate(decompressBytes);
    decompression.end();
    String jsonString = new String(Arrays.copyOfRange(decompressBytes, 0, decompressLength));
    // Get TLS.Sig from json
    JSONObject jsonObject = new JSONObject(jsonString);
    String sigTLS = jsonObject.getString("TLS.sig");
    // debase64 TLS.Sig to get serailString
    byte[] signatureBytes = decoder.decode(sigTLS.getBytes(Charset.forName("UTF-8")));
    try {
        String strSdkAppid = jsonObject.getString("TLS.sdk_appid");
        String sigTime = jsonObject.getString("TLS.time");
        String sigExpire = jsonObject.getString("TLS.expire_after");
        if (Integer.parseInt(strSdkAppid) != sdkAppid) {
            result.errMessage = new String("sdkappid " + strSdkAppid + " in tls sig not equal sdkappid " + sdkAppid + " in request");
            return result;
        }
        if (System.currentTimeMillis() / 1000 - Long.parseLong(sigTime) > Long.parseLong(sigExpire)) {
            result.errMessage = new String("TLS sig is out of date");
            return result;
        }
        // Get Serial String from json
        String SerialString = "TLS.appid_at_3rd:" + 0 + "\n" + "TLS.account_type:" + 0 + "\n" + "TLS.identifier:" + identifier + "\n" + "TLS.sdk_appid:" + sdkAppid + "\n" + "TLS.time:" + sigTime + "\n" + "TLS.expire_after:" + sigExpire + "\n";
        Reader reader = new CharArrayReader(publicKey.toCharArray());
        PEMParser parser = new PEMParser(reader);
        JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
        Object obj = parser.readObject();
        parser.close();
        PublicKey pubKeyStruct = converter.getPublicKey((SubjectPublicKeyInfo) obj);
        Signature signature = Signature.getInstance("SHA256withECDSA", "BC");
        signature.initVerify(pubKeyStruct);
        signature.update(SerialString.getBytes(Charset.forName("UTF-8")));
        boolean bool = signature.verify(signatureBytes);
        result.expireTime = Integer.parseInt(sigExpire);
        result.initTime = Integer.parseInt(sigTime);
        result.verifyResult = bool;
    } catch (Exception e) {
        e.printStackTrace();
        result.errMessage = "Failed in checking sig";
    }
    return result;
}
Also used : Base64(org.apache.commons.codec.binary.Base64) PublicKey(java.security.PublicKey) CharArrayReader(java.io.CharArrayReader) Reader(java.io.Reader) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) IOException(java.io.IOException) DataFormatException(java.util.zip.DataFormatException) CharArrayReader(java.io.CharArrayReader) JSONObject(org.json.JSONObject) PEMParser(org.bouncycastle.openssl.PEMParser) Signature(java.security.Signature) Inflater(java.util.zip.Inflater) JSONObject(org.json.JSONObject) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 100 with Base64.encodeBase64String

use of org.apache.commons.codec.binary.Base64.encodeBase64String in project xian by happyyangyuan.

the class Authenticator method getBasicAuthorizationClientCredentials.

public static String[] getBasicAuthorizationClientCredentials(HttpRequest req) {
    // extract Basic Authorization header
    String authHeader = req.headers().get(HttpHeaderNames.AUTHORIZATION);
    String[] clientCredentials = new String[2];
    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, Charset.forName("UTF-8"));
        // client_id:client_secret - should be changed by client password
        String[] str = decoded.split(":");
        if (str.length == 2) {
            clientCredentials[0] = str[0];
            clientCredentials[1] = str[1];
        }
    }
    return clientCredentials;
}
Also used : Base64(org.apache.commons.codec.binary.Base64)

Aggregations

Base64 (org.apache.commons.codec.binary.Base64)135 IOException (java.io.IOException)30 Test (org.junit.Test)29 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)12 InputStream (java.io.InputStream)11 HttpServletRequest (javax.servlet.http.HttpServletRequest)11 HttpServletResponse (javax.servlet.http.HttpServletResponse)11 Base64.encodeBase64String (org.apache.commons.codec.binary.Base64.encodeBase64String)11 ByteArrayInputStream (java.io.ByteArrayInputStream)10 HashMap (java.util.HashMap)10 SecretKeySpec (javax.crypto.spec.SecretKeySpec)9 MessageDigest (java.security.MessageDigest)8 File (java.io.File)7 UnsupportedEncodingException (java.io.UnsupportedEncodingException)7 URL (java.net.URL)7 Mac (javax.crypto.Mac)7 ServletException (javax.servlet.ServletException)7 X509Certificate (java.security.cert.X509Certificate)6 FileNotFoundException (java.io.FileNotFoundException)5 Signature (java.security.Signature)5