当前位置: 首页>>代码示例>>Java>>正文


Java Base64Utility类代码示例

本文整理汇总了Java中org.apache.cxf.common.util.Base64Utility的典型用法代码示例。如果您正苦于以下问题:Java Base64Utility类的具体用法?Java Base64Utility怎么用?Java Base64Utility使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


Base64Utility类属于org.apache.cxf.common.util包,在下文中一共展示了Base64Utility类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: createJWT

import org.apache.cxf.common.util.Base64Utility; //导入依赖的package包/类
public String createJWT(String username, Set<String> groups)
    throws GeneralSecurityException, IOException {
  // Create and Base64 encode the header portion of the JWT
  JsonObject headerObj =
      Json.createObjectBuilder()
          .add("alg", "RS256") /* Algorithm used */
          .add("typ", "JWT") /* Type of token */
          // .add("kid", "default") /* Hint about which key to use to sign, but the signature is
          // invalid when I include this. */
          .build();
  String headerEnc = Base64Utility.encode(headerObj.toString().getBytes(), true);

  // Create and Base64 encode the claims portion of the JWT
  JsonObject claimsObj =
      Json.createObjectBuilder()
          .add("exp", (System.currentTimeMillis() / 1000) + 300) /* Expire time */
          .add("iat", (System.currentTimeMillis() / 1000)) /* Issued time */
          .add("aud", "acmeGifts") /* Audience */
          .add("jti", Long.toHexString(System.nanoTime())) /* Unique value */
          .add("sub", username) /* Subject */
          .add("upn", username) /* Subject again */
          .add("iss", JWT_ISSUER) /* Issuer */
          .add("groups", getGroupArray(groups)) /* Group list */
          .build();
  String claimsEnc = Base64Utility.encode(claimsObj.toString().getBytes(), true);
  String headerClaimsEnc = headerEnc + "." + claimsEnc;

  // Open the keystore that the server will use to validate the JWT
  KeyStore ks = KeyStore.getInstance("JCEKS");
  InputStream ksStream = this.getClass().getResourceAsStream("/keystore.jceks");
  char[] password = new String("secret").toCharArray();
  ks.load(ksStream, password);

  // Get the private key to use to sign the JWT.  Normally we would not do this but
  // we are pretending to be the user service here.
  KeyStore.ProtectionParameter keyPassword = new KeyStore.PasswordProtection(password);
  KeyStore.PrivateKeyEntry privateKeyEntry =
      (KeyStore.PrivateKeyEntry) ks.getEntry("default", keyPassword);
  PrivateKey privateKey = privateKeyEntry.getPrivateKey();

  // Sign the JWT
  Signature sig = Signature.getInstance(JWT_ALGORITHM);
  sig.initSign(privateKey);
  sig.update(headerClaimsEnc.getBytes());
  String sigEnc = Base64Utility.encode(sig.sign(), true);

  // Lets just check......
  String jwtEnc = headerClaimsEnc + "." + sigEnc;
  java.security.cert.Certificate cert = ks.getCertificate("default");
  PublicKey publicKey = cert.getPublicKey();
  validateJWT("Bearer " + jwtEnc, publicKey);

  // Return the complete JWT (header, claims, signature).
  return jwtEnc;
}
 
开发者ID:OpenLiberty,项目名称:sample-acmegifts,代码行数:56,代码来源:JWTVerifier.java

示例2: validateJWT

import org.apache.cxf.common.util.Base64Utility; //导入依赖的package包/类
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());
  }
}
 
开发者ID:OpenLiberty,项目名称:sample-acmegifts,代码行数:29,代码来源:JWTVerifier.java

示例3: getPublicKey

import org.apache.cxf.common.util.Base64Utility; //导入依赖的package包/类
/**
 * 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));
}
 
开发者ID:OpenLiberty,项目名称:sample-acmegifts,代码行数:27,代码来源:JWTVerifier.java

示例4: main

import org.apache.cxf.common.util.Base64Utility; //导入依赖的package包/类
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);
}
 
开发者ID:shawn-gogh,项目名称:myjavacode,代码行数:19,代码来源:RestRequestByCxf.java

示例5: getService

import org.apache.cxf.common.util.Base64Utility; //导入依赖的package包/类
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;
        }
    }
 
开发者ID:geoserver,项目名称:geofence,代码行数:20,代码来源:GeoFenceClient.java

示例6: calculateSignature

import org.apache.cxf.common.util.Base64Utility; //导入依赖的package包/类
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;
}
 
开发者ID:antoniomaria,项目名称:gazpachoquest,代码行数:22,代码来源:HmacAuthInterceptor.java

示例7: writeObject

import org.apache.cxf.common.util.Base64Utility; //导入依赖的package包/类
@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));
    }
}
 
开发者ID:claudemamo,项目名称:jruby-cxf,代码行数:17,代码来源:Base64Type.java

示例8: build

import org.apache.cxf.common.util.Base64Utility; //导入依赖的package包/类
/**
 * This method returns an instance of an implementation the specified {@code clazz} (which should be a REST service
 * interface, e.g. TablemanagementRestService.class). <br/>
 * The caller must take care that no parameter value is equal to {@code NULL}. <br/>
 * The caller will be authenticated using basic authentication with the provided credentials. The method
 * {@code setLocalServerPort} MUST be called in advance.
 *
 * @param <T> The return type.
 * @param clazz This must be an interface type.
 * @param userName The userName for basic authentication.
 * @param tmpPassword The password for basic authentication.
 * @param tmpUrl The URL through which the server is reached.
 * @return A REST proxy of type {@code T}
 */
public <T extends RestService> T build(Class<T> clazz, String userName, String tmpPassword, String tmpUrl) {

  JAXRSClientFactoryBean factoryBean = new JAXRSClientFactoryBean();
  factoryBean.setAddress(tmpUrl);
  factoryBean.setHeaders(new HashMap<String, String>());
  // example for basic auth
  String payload = userName + ":" + tmpPassword;
  String authorizationHeader = "Basic " + Base64Utility.encode(payload.getBytes());
  factoryBean.getHeaders().put("Authorization", Arrays.asList(authorizationHeader));
  factoryBean.setProviders(Arrays.asList(this.jacksonJsonProvider));

  factoryBean.setServiceClass(clazz);
  return factoryBean.create(clazz);
}
 
开发者ID:oasp,项目名称:oasp-tutorial-sources,代码行数:29,代码来源:RestTestClientBuilder.java

示例9: createSecurityQuestionAbortMessage

import org.apache.cxf.common.util.Base64Utility; //导入依赖的package包/类
public static void createSecurityQuestionAbortMessage(ContainerRequestContext requestCtx, String secQChallenge){
	String challenge = "";
	if (StringUtils.isNotBlank(secQChallenge)) {
		challenge = " " + Base64Utility.encode(secQChallenge.getBytes());
	}
	
	requestCtx.abortWith(Response.status(Status.UNAUTHORIZED)
			.header("WWW-Authenticate",
					RestAuthenticationMethod.SECURITY_QUESTIONS.getMethod() + challenge)
			.build());
}
 
开发者ID:Pardus-Engerek,项目名称:engerek,代码行数:12,代码来源:RestServiceUtil.java

示例10: createSecurityQuestionAbortMessage

import org.apache.cxf.common.util.Base64Utility; //导入依赖的package包/类
public static void createSecurityQuestionAbortMessage(ContainerRequestContext requestCtx, String secQChallenge){
	String challenge = "";
	if (StringUtils.isNotBlank(secQChallenge)) {
		challenge = " " + Base64Utility.encode(secQChallenge.getBytes());
	}

	requestCtx.abortWith(Response.status(Status.UNAUTHORIZED)
			.header("WWW-Authenticate",
					RestAuthenticationMethod.SECURITY_QUESTIONS.getMethod() + challenge)
			.build());
}
 
开发者ID:Evolveum,项目名称:midpoint,代码行数:12,代码来源:RestServiceUtil.java

示例11: reconstituteJavaObject

import org.apache.cxf.common.util.Base64Utility; //导入依赖的package包/类
private Object reconstituteJavaObject(MessageReader reader) throws DatabindingException {

        try {
            ByteArrayInputStream in = new ByteArrayInputStream(Base64Utility
                                                                   .decode(reader.getValue().trim()));
            return new ObjectInputStream(in).readObject();
        } catch (Exception e) {
            throw new DatabindingException("Unable to reconstitute serialized object", e);
        }
    }
 
开发者ID:claudemamo,项目名称:jruby-cxf,代码行数:11,代码来源:ObjectType.java

示例12: encode

import org.apache.cxf.common.util.Base64Utility; //导入依赖的package包/类
public static String encode( String uid, String password )
{
    return "Basic " + Base64Utility.encode( ( uid + ":" + password ).getBytes() );
}
 
开发者ID:ruikom,项目名称:apache-archiva,代码行数:5,代码来源:AbstractDownloadTest.java

示例13: createClient

import org.apache.cxf.common.util.Base64Utility; //导入依赖的package包/类
private static WebClient createClient(String uri) {
    WebClient client = WebClient.create(BASE_REST_URI + uri);
    String auth = "Basic " + Base64Utility.encode("kermit:kermit".getBytes());
    client.header("Authorization", auth);
    return client;
}
 
开发者ID:shawn-gogh,项目名称:myjavacode,代码行数:7,代码来源:RestRequestTandemUseSpringRest.java

示例14: createClient

import org.apache.cxf.common.util.Base64Utility; //导入依赖的package包/类
private static WebClient createClient(String uri) {
    WebClient client = WebClient.create(BASE_REST_URI + uri);
    String auth = "Basic " + Base64Utility.encode("kermit:000000".getBytes());
    client.header("Authorization", auth);
    return client;
}
 
开发者ID:shawn-gogh,项目名称:myjavacode,代码行数:7,代码来源:RestRequestForDiagramViewer.java

示例15: runPs

import org.apache.cxf.common.util.Base64Utility; //导入依赖的package包/类
public CommandOutput runPs(String script) {
    //@[email protected] must use utf16 little endian on windows
    String base64Script = Base64Utility.encode(script.getBytes(StandardCharsets.UTF_8));
    String command = String.format("powershell -encodedcommand %s", base64Script);
    return runCmd(command);
}
 
开发者ID:apifocal,项目名称:wsman4j,代码行数:7,代码来源:Session.java


注:本文中的org.apache.cxf.common.util.Base64Utility类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。