org.apache.cxf.common.util.Base64Utility Java Examples

The following examples show how to use org.apache.cxf.common.util.Base64Utility. 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: AuthorizationFilter.java    From iaf with Apache License 2.0 6 votes vote down vote up
private boolean login(ContainerRequestContext requestContext) {
	String authorization = requestContext.getHeaderString("Authorization");
	String[] parts = authorization.split(" ");
	if (parts.length != 2 || !"Basic".equals(parts[0])) {
		return false;
	}

	String decodedValue = null;
	try {
		decodedValue = new String(Base64Utility.decode(parts[1]));
	} catch (Base64Exception ex) {
		return false;
	}
	String[] namePassword = decodedValue.split(":");

	try {
		request.login(namePassword[0], namePassword[1]);
	} catch (Exception e) {
		return false;
	}
	return true;
}
 
Example #2
Source File: Base64Type.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public void writeObject(Object object,
                        MessageWriter writer,
                        Context context) throws DatabindingException {
    boolean mtomEnabled = context.isMtomEnabled();
    if (mtomEnabled) {
        optimizedType.writeObject(object, writer, context);
        return;
    }

    byte[] data = (byte[])object;

    if (data != null && data.length > 0) {
        writer.writeValue(Base64Utility.encode(data));
    }
}
 
Example #3
Source File: WSS4JTokenConverter.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static void convertToken(Message msg, Principal p) {
    if (p instanceof UsernameTokenPrincipal) {
        UsernameTokenPrincipal utp = (UsernameTokenPrincipal)p;
        String nonce = null;
        if (utp.getNonce() != null) {
            nonce = Base64Utility.encode(utp.getNonce());
        }
        msg.put(org.apache.cxf.common.security.SecurityToken.class,
                new UsernameToken(utp.getName(),
                                  utp.getPassword(),
                                  utp.getPasswordType(),
                                  utp.isPasswordDigest(),
                                  nonce,
                                  utp.getCreatedTime()));

    }
}
 
Example #4
Source File: OAuthUtils.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static boolean compareTlsCertificates(TLSSessionInfo tlsInfo,
                                      List<String> base64EncodedCerts) {
    Certificate[] clientCerts = tlsInfo.getPeerCertificates();
    if (clientCerts.length == base64EncodedCerts.size()) {
        try {
            for (int i = 0; i < clientCerts.length; i++) {
                X509Certificate x509Cert = (X509Certificate)clientCerts[i];
                byte[] encodedKey = x509Cert.getEncoded();
                byte[] clientKey = Base64Utility.decode(base64EncodedCerts.get(i));
                if (!Arrays.equals(encodedKey, clientKey)) {
                    return false;
                }
            }
            return true;
        } catch (Exception ex) {
            // throw exception later
        }
    }
    return false;
}
 
Example #5
Source File: STSRESTTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testIssueSAML2TokenPlain() throws Exception {
    WebClient client = webClient()
        .path("saml2.0")
        .accept(MediaType.TEXT_PLAIN);

    String encodedAssertion = client.get(String.class);
    assertNotNull(encodedAssertion);

    byte[] deflatedToken = Base64Utility.decode(encodedAssertion);
    InputStream inputStream = CompressionUtils.inflate(deflatedToken);
    Document doc =
        StaxUtils.read(new InputStreamReader(inputStream, StandardCharsets.UTF_8));

    // Process the token
    SamlAssertionWrapper assertion = validateSAMLToken(doc);
    assertTrue(assertion.getSaml2() != null && assertion.getSaml1() == null);
}
 
Example #6
Source File: CustomerMetricsInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public void handleMessage(Message message) throws Fault {
    ExchangeMetrics m = message.getExchange().get(ExchangeMetrics.class);
    if (m != null) {
        Map<String, List<String>> h = CastUtils.cast((Map<?, ?>)message.get(Message.PROTOCOL_HEADERS));
        String auth = h.get("Authorization").toString();
        auth = auth.substring(auth.indexOf(' ') + 1);
        try {
            auth = new String(Base64Utility.decode(auth));
        } catch (Base64Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        auth = auth.substring(0, auth.indexOf(':'));
        Customer c = customers.get(auth);
        if (c == null) {
            throw new RuntimeException("Not authorized");
        }
        m.addContext(c.getMetricsContext(registry));
        message.getExchange().put(Customer.class, c);
    }
}
 
Example #7
Source File: AbstractSpnegoAuthSupplier.java    From cxf with Apache License 2.0 6 votes vote down vote up
public String getAuthorization(AuthorizationPolicy authPolicy,
                               URI currentURI,
                               Message message) {
    if (!HttpAuthHeader.AUTH_TYPE_NEGOTIATE.equals(authPolicy.getAuthorizationType())) {
        return null;
    }
    try {
        String spn = getCompleteServicePrincipalName(currentURI);

        boolean useKerberosOid = MessageUtils.getContextualBoolean(message, PROPERTY_USE_KERBEROS_OID);
        Oid oid = new Oid(useKerberosOid ? KERBEROS_OID : SPNEGO_OID);

        byte[] token = getToken(authPolicy, spn, oid, message);
        return HttpAuthHeader.AUTH_TYPE_NEGOTIATE + " " + Base64Utility.encode(token);
    } catch (LoginException | GSSException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
 
Example #8
Source File: URIResolver.java    From cxf with Apache License 2.0 6 votes vote down vote up
private HttpURLConnection createInputStream() throws IOException {
    HttpURLConnection huc = (HttpURLConnection)url.openConnection();

    String host = SystemPropertyAction.getPropertyOrNull("http.proxyHost");
    if (host != null) {
        //comment out unused port to pass pmd check
        /*String ports = SystemPropertyAction.getProperty("http.proxyPort");
        int port = 80;
        if (ports != null) {
            port = Integer.parseInt(ports);
        }*/

        String username = SystemPropertyAction.getPropertyOrNull("http.proxy.user");
        String password = SystemPropertyAction.getPropertyOrNull("http.proxy.password");

        if (username != null && password != null) {
            String encoded = Base64Utility.encode((username + ":" + password).getBytes());
            huc.setRequestProperty("Proxy-Authorization", "Basic " + encoded);
        }
    }
    huc.setConnectTimeout(30000);
    huc.setReadTimeout(60000);
    is = huc.getInputStream();
    return huc;
}
 
Example #9
Source File: RestRequestByCxf.java    From activiti-in-action-codes with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    // 创建client对象
    WebClient client = WebClient.create(REST_URI);

    // Basic Auth身份认证
    String auth = "Basic " + Base64Utility.encode("kermit:kermit".getBytes());
    client.header("Authorization", auth);

    // 获取响应内容
    Response response = client.get();
    InputStream stream = (InputStream) response.getEntity();

    // 转换并输出响应结果
    StringWriter writer = new StringWriter();
    IOUtils.copy(stream, writer, "UTF-8");
    String respText = writer.toString();
    System.out.println(respText);
}
 
Example #10
Source File: Base64DecoderStream.java    From cxf with Apache License 2.0 6 votes vote down vote up
/**
 * Decode a requested number of bytes of data into a buffer.
 *
 * @return true if we were able to obtain more data, false otherwise.
 */
private boolean decodeStreamData() throws IOException {
    decodedIndex = 0;

    // fill up a data buffer with input data
    int readCharacters = fillEncodedBuffer();

    if (readCharacters > 0) {
        try {
            decodedChars = Base64Utility.decodeChunk(encodedChars, 0, readCharacters);
        } catch (Base64Exception e) {
            throw new IOException(e);
        }
        decodedCount = decodedChars.length;
        return true;
    }
    return false;
}
 
Example #11
Source File: HmacAuthInterceptor.java    From gazpachoquest with GNU General Public License v3.0 6 votes vote down vote up
public static String calculateSignature(String data, String key) {
    logger.debug("Signing with algorithm {} the string: {} ", HMAC_SHA1_ALGORITHM, data);
    String result;
    try {
        // get an hmac_sha1 key from the raw key bytes
        SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);

        // get an hmac_sha1 Mac instance and initialize with the signing key
        Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
        mac.init(signingKey);

        // compute the hmac on input data bytes
        byte[] rawHmac = mac.doFinal(data.getBytes());

        // base64-encode the hmac
        result = Base64Utility.encode(rawHmac);
    } catch (Exception e) {
        throw new IllegalStateException("Failed to generate HMAC : " + e.getMessage());
    }
    return result;
}
 
Example #12
Source File: GeoFenceClient.java    From geofence with GNU General Public License v2.0 6 votes vote down vote up
protected <T>T getService(Class<T> clazz, String endpoint) {
        if(services.containsKey(clazz))
            return (T)services.get(clazz);

        if(restUrl == null)
            new IllegalStateException("GeoFence URL not set");

        synchronized(services) {
//            T proxy = JAXRSClientFactory.create(restUrl, clazz, username, password, null);
            
            T proxy = JAXRSClientFactory.create(restUrl+"/"+endpoint, clazz);
            String authorizationHeader = "Basic "  + Base64Utility.encode((username+":"+password).getBytes());
            WebClient.client(proxy).header("Authorization", authorizationHeader);

//        WebClient.client(proxy).accept("text/xml");
            services.put(clazz, proxy);
            return proxy;
        }
    }
 
Example #13
Source File: JWTVerifier.java    From sample-acmegifts with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Get the public key that is used to verify the JWT from the user service. We assume the key is
 * an RSA key.
 *
 * @throws NoSuchAlgorithmException
 */
private PublicKey getPublicKey()
    throws Base64Exception, InvalidKeySpecException, NoSuchAlgorithmException {
  String url =
      "https://" + libertyHostname + ":" + libertySslPort + "/jwt/ibm/api/jwtUserBuilder/jwk";
  Response response = processRequest(url, "GET", null, null);
  assertEquals(
      "HTTP response code should have been " + Status.OK.getStatusCode() + ".",
      Status.OK.getStatusCode(),
      response.getStatus());

  // Liberty returns the keys in an array.  We'll grab the first one (there
  // should only be one).
  JsonObject jwkResponse = toJsonObj(response.readEntity(String.class));
  JsonArray jwkArray = jwkResponse.getJsonArray("keys");
  JsonObject jwk = jwkArray.getJsonObject(0);
  BigInteger modulus = new BigInteger(1, Base64Utility.decode(jwk.getString("n"), true));
  BigInteger publicExponent = new BigInteger(1, Base64Utility.decode(jwk.getString("e"), true));
  return KeyFactory.getInstance("RSA")
      .generatePublic(new RSAPublicKeySpec(modulus, publicExponent));
}
 
Example #14
Source File: AttachmentSerializer.java    From cxf with Apache License 2.0 5 votes vote down vote up
private int encodeBase64(InputStream input, OutputStream output, int bufferSize) throws IOException {
    int avail = input.available();
    if (avail > 262143) {
        //must be divisible by 3
        avail = 262143;
    }
    if (avail > bufferSize) {
        bufferSize = avail;
    }
    final byte[] buffer = new byte[bufferSize];
    int n = input.read(buffer);
    int total = 0;
    while (-1 != n) {
        if (n == 0) {
            throw new IOException("0 bytes read in violation of InputStream.read(byte[])");
        }
        //make sure n is divisible by 3
        int left = n % 3;
        n -= left;
        if (n > 0) {
            Base64Utility.encodeAndStream(buffer, 0, n, output);
            total += n;
        }
        if (left != 0) {
            for (int x = 0; x < left; ++x) {
                buffer[x] = buffer[n + x];
            }
            n = input.read(buffer, left, buffer.length - left);
            if (n == -1) {
                // we've hit the end, but still have stuff left, write it out
                Base64Utility.encodeAndStream(buffer, 0, left, output);
                total += left;
            }
        } else {
            n = input.read(buffer);
        }
    }
    return total;
}
 
Example #15
Source File: ServiceListJAASAuthenticator.java    From cxf with Apache License 2.0 5 votes vote down vote up
private static String base64Decode(String srcString) {
    byte[] transformed = null;
    try {
        transformed = Base64Utility.decode(srcString);
        return new String(transformed, "ISO-8859-1");
    } catch (UnsupportedEncodingException | Base64Exception e) {
        return srcString;
    }
}
 
Example #16
Source File: SamlPostBindingFilter.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected String encodeAuthnRequest(Element authnRequest) throws IOException {
    String requestMessage = DOM2Writer.nodeToString(authnRequest);

    byte[] deflatedBytes = null;
    // Not correct according to the spec but required by some IDPs.
    if (useDeflateEncoding) {
        DeflateEncoderDecoder encoder = new DeflateEncoderDecoder();
        deflatedBytes = encoder.deflateToken(requestMessage.getBytes(StandardCharsets.UTF_8));
    } else {
        deflatedBytes = requestMessage.getBytes(StandardCharsets.UTF_8);
    }

    return Base64Utility.encode(deflatedBytes);
}
 
Example #17
Source File: SamlRedirectBindingFilter.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected String encodeAuthnRequest(Element authnRequest) throws IOException {
    String requestMessage = DOM2Writer.nodeToString(authnRequest);

    DeflateEncoderDecoder encoder = new DeflateEncoderDecoder();
    byte[] deflatedBytes = encoder.deflateToken(requestMessage.getBytes(StandardCharsets.UTF_8));

    return Base64Utility.encode(deflatedBytes);
}
 
Example #18
Source File: DeflateEncoderDecoderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testInflateDeflateBase64() throws Exception {
    DeflateEncoderDecoder inflater = new DeflateEncoderDecoder();
    byte[] deflated = inflater.deflateToken("valid_grant".getBytes());
    String base64String = Base64Utility.encode(deflated);
    byte[] base64decoded = Base64Utility.decode(base64String);
    InputStream is = inflater.inflateToken(base64decoded);
    assertNotNull(is);
    assertEquals("valid_grant", IOUtils.readStringFromStream(is));
}
 
Example #19
Source File: AbstractSamlOutInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected String encodeToken(String assertion) throws Base64Exception {
    byte[] tokenBytes = assertion.getBytes(StandardCharsets.UTF_8);

    if (useDeflateEncoding) {
        tokenBytes = new DeflateEncoderDecoder().deflateToken(tokenBytes);
    }
    StringWriter writer = new StringWriter();
    Base64Utility.encode(tokenBytes, 0, tokenBytes.length, writer);
    return writer.toString();
}
 
Example #20
Source File: JWTVerifier.java    From sample-acmegifts with Eclipse Public License 1.0 5 votes vote down vote up
public void validateJWT(String authHeader, PublicKey publicKey) {
  assertNotNull("Authorization header was not present in response", authHeader);
  assertTrue("Authorization header does not contain a bearer", authHeader.startsWith("Bearer "));

  StringTokenizer st = new StringTokenizer(authHeader.substring(7), ".");
  assertTrue("JWT does not contain three parts", st.countTokens() == 3);

  String jwtHeaderEnc = st.nextToken();
  String jwtClaimsEnc = st.nextToken();
  String jwtSigEnc = st.nextToken();

  try {
    // Decode the signature we got from the server
    byte[] jwtExpectedSig = Base64Utility.decode(jwtSigEnc, true);

    // Validate the signature.
    Signature sig = Signature.getInstance(JWT_ALGORITHM);
    sig.initVerify(publicKey);
    sig.update(new String(jwtHeaderEnc + "." + jwtClaimsEnc).getBytes());
    assertTrue("JWT expected and actual signatures don't match", sig.verify(jwtExpectedSig));
  } catch (Base64Exception be) {
    Assert.fail("Exception decoding JWT signature: " + be.toString());
  } catch (Throwable t) {
    System.out.println(t.toString());
    t.printStackTrace(System.out);
    Assert.fail("Exception validating JWT signature: " + t.toString());
  }
}
 
Example #21
Source File: AuthorizationUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static String[] getBasicAuthParts(String basicAuthData) {
    final String authDecoded;
    try {
        authDecoded = new String(Base64Utility.decode(basicAuthData));
    } catch (Exception ex) {
        throw ExceptionUtils.toNotAuthorizedException(ex, null);
    }
    String[] authInfo = authDecoded.split(":");
    if (authInfo.length == 2) {
        return authInfo;
    }
    throw ExceptionUtils.toNotAuthorizedException(null, null);
}
 
Example #22
Source File: KerberosAuthenticationFilter.java    From cxf with Apache License 2.0 5 votes vote down vote up
private byte[] getServiceTicket(String encodedServiceTicket) {
    try {
        return Base64Utility.decode(encodedServiceTicket);
    } catch (Base64Exception ex) {
        throw ExceptionUtils.toNotAuthorizedException(null, getFaultResponse());
    }
}
 
Example #23
Source File: Base64DecoderStream.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Fill our buffer of input characters for decoding from the
 * stream.  This will attempt read a full buffer, but will
 * terminate on an EOF or read error.  This will filter out
 * non-Base64 encoding chars and will only return a valid
 * multiple of 4 number of bytes.
 *
 * @return The count of characters read.
 */
private int fillEncodedBuffer() throws IOException {
    int readCharacters = 0;

    while (true) {
        // get the next character from the stream
        int ch = in.read();
        // did we hit an EOF condition?
        if (ch == -1) {
            // now check to see if this is normal, or potentially an error
            // if we didn't get characters as a multiple of 4, we may need to complain about this.
            if ((readCharacters % 4) != 0) {
                throw new IOException("Base64 encoding error, data truncated: " + readCharacters + " "
                                      + new String(encodedChars, 0, readCharacters));
            }
            // return the count.
            return readCharacters;
        } else if (Base64Utility.isValidBase64(ch)) {
            // if this character is valid in a Base64 stream, copy it to the buffer.
            encodedChars[readCharacters++] = (char)ch;
            // if we've filled up the buffer, time to quit.
            if (readCharacters >= encodedChars.length) {
                return readCharacters;
            }
        }

        // we're filtering out whitespace and CRLF characters, so just ignore these
    }
}
 
Example #24
Source File: CryptoUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static Certificate decodeCertificate(String encodedCert) {
    try {
        byte[] decoded = Base64Utility.decode(encodedCert);
        return CertificateFactory.getInstance("X.509").generateCertificate(new ByteArrayInputStream(decoded));
    } catch (Exception ex) {
        throw new SecurityException(ex);
    }
}
 
Example #25
Source File: AbstractSamlResponseCreator.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
protected String encodeResponse(Element response) throws IOException {
    String responseMessage = DOM2Writer.nodeToString(response);
    LOG.debug("Created Response: {}", responseMessage);

    if (supportDeflateEncoding) {
        DeflateEncoderDecoder encoder = new DeflateEncoderDecoder();
        byte[] deflatedBytes = encoder.deflateToken(responseMessage.getBytes(StandardCharsets.UTF_8));

        return Base64Utility.encode(deflatedBytes);
    }

    return Base64Utility.encode(responseMessage.getBytes());
}
 
Example #26
Source File: AuthnRequestParser.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
protected RequestAbstractType extractRequest(RequestContext context, String samlRequest) throws Exception {
    byte[] deflatedToken = Base64Utility.decode(samlRequest);
    String httpMethod = WebUtils.getHttpServletRequest(context).getMethod();

    InputStream tokenStream = supportDeflateEncoding || "GET".equals(httpMethod)
         ? new DeflateEncoderDecoder().inflateToken(deflatedToken)
             : new ByteArrayInputStream(deflatedToken);

    Document responseDoc = StaxUtils.read(new InputStreamReader(tokenStream, StandardCharsets.UTF_8));
    if (LOG.isDebugEnabled()) {
        LOG.debug(DOM2Writer.nodeToString(responseDoc));
    }
    return (RequestAbstractType)OpenSAMLUtil.fromDom(responseDoc.getDocumentElement());
}
 
Example #27
Source File: JAXRSSamlTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private String encodeToken(String assertion) throws Base64Exception {
    byte[] tokenBytes = assertion.getBytes(StandardCharsets.UTF_8);

    tokenBytes = new DeflateEncoderDecoder().deflateToken(tokenBytes);
    StringWriter writer = new StringWriter();
    Base64Utility.encode(tokenBytes, 0, tokenBytes.length, writer);
    return writer.toString();
}
 
Example #28
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
private static String encodeAuthnRequest(XMLObject request) throws WSSecurityException {
    Document doc = DOMUtils.createDocument();
    doc.appendChild(doc.createElement("root"));
    String requestMessage = DOM2Writer.nodeToString(OpenSAMLUtil.toDom(request, doc));

    DeflateEncoderDecoder encoder = new DeflateEncoderDecoder();
    byte[] deflatedBytes = encoder.deflateToken(requestMessage.getBytes(UTF_8));

    return Base64Utility.encode(deflatedBytes);
}
 
Example #29
Source File: AttachmentProviderXMLClientServerTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void verifyAttachment(List<Element> atts, String contentId, String value) {

        for (Element expElem : atts) {
            String child = expElem.getFirstChild().getNodeValue();
            String contentIdVal = expElem.getAttribute("contentId");
            if (contentId.equals(contentIdVal)
                && (Base64Utility.encode(value.getBytes()).equals(child)
                    || Base64Utility.encode((value + "\n").getBytes()).equals(child))) {
                return;
            }
        }

        fail("No encoded attachment with id " + contentId + " found");
    }
 
Example #30
Source File: PushBack401.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * This function extracts the user:pass token from
 * the Authorization:Basic header. It returns a two element
 * String array, the first being the userid, the second
 * being the password. It returns null, if it cannot parse.
 */
private String[] extractUserPass(String token) {
    try {
        byte[] userpass = Base64Utility.decode(token);
        String up = IOUtils.newStringFromBytes(userpass);
        String user = up.substring(0, up.indexOf(':'));
        String pass = up.substring(up.indexOf(':') + 1);
        return new String[] {user, pass};
    } catch (Exception e) {
        return null;
    }

}