本文整理汇总了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;
}
示例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());
}
}
示例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));
}
示例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);
}
示例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;
}
}
示例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;
}
示例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));
}
}
示例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);
}
示例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());
}
示例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());
}
示例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);
}
}
示例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() );
}
示例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;
}
示例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;
}
示例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);
}