本文整理汇总了Java中org.apache.shiro.codec.Base64类的典型用法代码示例。如果您正苦于以下问题:Java Base64类的具体用法?Java Base64怎么用?Java Base64使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
Base64类属于org.apache.shiro.codec包,在下文中一共展示了Base64类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: getCredentials
import org.apache.shiro.codec.Base64; //导入依赖的package包/类
/**
*
* @param info the AuthenticationInfo from which to retrieve the credentials which assumed to be in already-hashed form.
* @return a {@link Hash Hash} instance representing the given AuthenticationInfo's stored credentials.
*/
protected Object getCredentials(AuthenticationInfo info) {
Object credentials = info.getCredentials();
byte[] storedBytes = toBytes(credentials);
if (credentials instanceof String || credentials instanceof char[]) {
//account.credentials were a char[] or String, so
//we need to do text decoding first:
if (isStoredCredentialsHexEncoded()) {
storedBytes = Hex.decode(storedBytes);
} else {
storedBytes = Base64.decode(storedBytes);
}
}
AbstractHash hash = newHashInstance();
hash.setBytes(storedBytes);
return hash;
}
示例2: passwordsMatch
import org.apache.shiro.codec.Base64; //导入依赖的package包/类
public boolean passwordsMatch(Object submittedPlaintext, String encrypted) {
ByteSource plaintextBytes = ByteSource.Util.bytes(submittedPlaintext);
if (encrypted == null || encrypted.length() == 0) {
return plaintextBytes == null || plaintextBytes.isEmpty();
} else {
if (plaintextBytes == null || plaintextBytes.isEmpty()) {
return false;
}
}
String plaintext = new String(plaintextBytes.getBytes());
String[] tokens = encrypted.split("\\$");
int iterations = Integer.parseInt(tokens[1]);
byte[] salt = tokens[2].getBytes();
String hash = tokens[3];
KeySpec spec = new PBEKeySpec(plaintext.toCharArray(), salt, iterations, 256);
try {
String algorithmName = getAlgorithmFullName(tokens[0]);
SecretKeyFactory f = SecretKeyFactory.getInstance(algorithmName);
return hash.equals(Base64.encodeToString(f.generateSecret(spec).getEncoded()));
} catch (Exception e) {
log.error(e.getMessage());
return false;
}
}
示例3: onPreHandle
import org.apache.shiro.codec.Base64; //导入依赖的package包/类
@Override
protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
Subject subject = SecurityUtils.getSubject();
if (!subject.isAuthenticated()) {
HttpServletRequest httpRequest = WebUtils.toHttp(request);
String authzHeader = httpRequest.getHeader(AUTHORIZATION_HEADER);
if (authzHeader != null) {
if (authzHeader.toLowerCase(Locale.ENGLISH).startsWith("basic")
|| authzHeader.toLowerCase(Locale.ENGLISH).startsWith("token")) {
String authToken = StringUtils.substringAfter(authzHeader, " ");
String decoded = Base64.decodeToString(authToken);
String userName = StringUtils.substringBefore(decoded, ":").trim();
String password = StringUtils.substringAfter(decoded, ":").trim();
if (userName.length() != 0 && password.length() != 0) {
UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
subject.login(token);
}
}
}
}
return true;
}
示例4: rememberSerializedIdentity
import org.apache.shiro.codec.Base64; //导入依赖的package包/类
/**
* Base64-encodes the specified serialized byte array and sets that base64-encoded String as the cookie value.
* <p/>
* The {@code subject} instance is expected to be a {@link WebSubject} instance with an HTTP Request/Response pair
* so an HTTP cookie can be set on the outgoing response. If it is not a {@code WebSubject} or that
* {@code WebSubject} does not have an HTTP Request/Response pair, this implementation does nothing.
*
* @param subject the Subject for which the identity is being serialized.
* @param serialized the serialized bytes to be persisted.
*/
protected void rememberSerializedIdentity(Subject subject, byte[] serialized) {
if (!WebUtils.isHttp(subject)) {
if (log.isDebugEnabled()) {
String msg = "Subject argument is not an HTTP-aware instance. This is required to obtain a servlet " +
"request and response in order to set the rememberMe cookie. Returning immediately and " +
"ignoring rememberMe operation.";
log.debug(msg);
}
return;
}
HttpServletRequest request = WebUtils.getHttpRequest(subject);
HttpServletResponse response = WebUtils.getHttpResponse(subject);
//base 64 encode it and store as a cookie:
String base64 = Base64.encodeToString(serialized);
Cookie template = getCookie(); //the class attribute is really a template for the outgoing cookies
Cookie cookie = new SimpleCookie(template);
cookie.setValue(base64);
cookie.saveTo(request, response);
}
示例5: main
import org.apache.shiro.codec.Base64; //导入依赖的package包/类
public static void main(String[] args) throws NoSuchAlgorithmException {
DefaultHashService hashService = new DefaultHashService(); // 默认算法SHA-512
SecureRandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();
randomNumberGenerator.setSeed("123".getBytes());
String salt = randomNumberGenerator.nextBytes().toHex();
HashRequest request = new HashRequest.Builder().setAlgorithmName("MD5")
.setSource(ByteSource.Util.bytes("123456")).setSalt(ByteSource.Util.bytes(salt)).setIterations(2)
.build();
String hex = hashService.computeHash(request).toHex();
System.out.println(salt);
System.out.println(hex);
KeyGenerator keygen = KeyGenerator.getInstance("AES");
SecretKey deskey = keygen.generateKey();
System.out.println(Base64.encodeToString(deskey.getEncoded()));
}
示例6: getCredentials
import org.apache.shiro.codec.Base64; //导入依赖的package包/类
/**
*
* @param info the {@code AuthenticationInfo} stored in the data store to be compared against the submitted authentication
* token's credentials.
* @return Signature = Base64( HMAC-SHA1( YourSecretAccessKeyID, UTF-8-Encoding-Of( StringToSign ) ) );
*/
@Override
protected Object getCredentials(AuthenticationInfo info) {
Object signature = null;
byte[] saltBytes = null;
if (info instanceof SaltedAuthenticationInfo) {
saltBytes = ((SaltedAuthenticationInfo) info).getCredentialsSalt().getBytes();
}
try {
String stringToSign = (String) info.getCredentials();
byte[] hmacSha1 = HmacSha1.hash(saltBytes, stringToSign);
signature = Base64.encodeToString(hmacSha1);
}
catch (Exception e) {
e.printStackTrace();
log.error(e.getMessage());
}
return signature;
}
示例7: rememberSerializedIdentity
import org.apache.shiro.codec.Base64; //导入依赖的package包/类
/**
* Base64-encodes the specified serialized byte array and sets that base64-encoded String as the cookie value.
* <p/>
* The {@code subject} instance is expected to be a {@link WebSubject} instance with an HTTP Request/Response pair
* so an HTTP cookie can be set on the outgoing response. If it is not a {@code WebSubject} or that
* {@code WebSubject} does not have an HTTP Request/Response pair, this implementation does nothing.
*
* @param subject the Subject for which the identity is being serialized.
* @param serialized the serialized bytes to be persisted.
*/
@Override
protected void rememberSerializedIdentity(Subject subject, byte[] serialized) {
if (! (subject instanceof ContextSource)) {
// if (log.isDebugEnabled()) {
// String msg = "Subject argument is not an HTTP-aware instance. This is required to obtain a servlet " +
// "request and response in order to set the rememberMe cookie. Returning immediately and " +
// "ignoring rememberMe operation.";
// log.debug(msg);
// }
return;
}
Context context = ((ContextSource) subject).getContext();
//base 64 encode it and store as a cookie
String base64 = Base64.encodeToString(serialized); // could be java.util.Base64
context.addCookie(Cookie.builder(getCookie()).setValue(base64).build()); // save the cookie
}
示例8: rememberSerializedIdentity
import org.apache.shiro.codec.Base64; //导入依赖的package包/类
@Override
protected void rememberSerializedIdentity(Subject subject, byte[] serialized) {
if (!WebUtils.isHttp(subject)) {
if (LOGGER.isDebugEnabled()) {
String msg = "Subject argument is not an HTTP-aware instance. This is required to obtain a servlet " +
"request and response in order to set the rememberMe cookie. Returning immediately and " +
"ignoring rememberMe operation.";
LOGGER.debug(msg);
}
return;
}
HttpServletRequest request = WebUtils.getHttpRequest(subject);
HttpServletResponse response = WebUtils.getHttpResponse(subject);
// base 64 encode it and store as a cookie:
String base64 = Base64.encodeToString(serialized);
// the class attribute is really a template for the outgoing cookies
Cookie cookie = getCookie();
cookie.setValue(base64);
cookie.saveTo(request, response);
}
示例9: main
import org.apache.shiro.codec.Base64; //导入依赖的package包/类
public static void main(String[] args) {
String base64="zGkG0zevFbnIioooS3MfnnbWeBUeiZrScKVJms0CZAdJ2MYTddPkvBHGmMhvgdKA5QJk8FSb9T1Y1tFlUnnCsIvcK+iX4cfrwD7voGdU5bW9AWjwNvl3BDrAgRf+hvjrI3T5nBTFeW7uI6GzfFrIx92qER9lQ97g19Dn555uwIzf0ULvc8jICZTraLLrf2avh1hy2kUJJblO6u5IHiBbAXBNitZ6W1yjLEWmSFnb+EsEWAGB3WwV1u1HZO045LB4G57UIH4QGM0xfJjWWeahiTS4j9IAEJBbghwfL1A5pdzFiXJzzA5GF85vtP+6jLwQfGaQJyv35PvNNsDmCqFe8eUSBLji5z5y/y+yKfZk9izXiEvFjKQ5kqMqKfLMp+Vn5OuO+syc4CfJL4PLI16vwVUPV1EWAzyxUhK7DtD5OMVcLPwVtwZ11dG88wkZtjXvBymLyGCj5/Tk8gTWYsdcNKD5i8WvbMLT45S4iWsZxa/5offIiCipkkqoqvxCppJLTzBoaR/wlqoa1Bc/cvpijiJTIbSCj+iFloQRdax1mMQ";
base64 = ensurePadding(base64);
byte[] decoded = Base64.decode(base64);
byte[] serialized = decoded;
CipherService cipherService = new AesCipherService();
if (cipherService != null) {
ByteSource byteSource = cipherService.decrypt(decoded, new byte[]{-112, -15, -2, 108, -116, 100, -28, 61, -99, 121, -104, -120, -59, -58, -102, 104});
serialized = byteSource.getBytes();
}
Serializer<PrincipalCollection> serializer = new DefaultSerializer<PrincipalCollection>();
;
System.out.println(serializer.deserialize(serialized));
SimplePrincipalCollection p=(SimplePrincipalCollection) serializer.deserialize(serialized);
System.out.println(p.getPrimaryPrincipal());
System.out.println(p.getRealmNames());
System.out.println(p);
}
示例10: checkPaybox
import org.apache.shiro.codec.Base64; //导入依赖的package包/类
/**
*
* @param signature
* La signature contenu dans l'url
* @param urlParam
* Liste des paramètres contenus dans l'url, privé du dernier : la signature
* @param pubKeyPath
* Le chemin de la clé publique Paybox
* @return
* @throws Exception
*/
public boolean checkPaybox(String signature, List<String> urlParam, String pubKeyPath) throws Exception {
String payboxParams = StringUtils.join(urlParam, "&");
log.debug("Liste des variables Paybox signées : {}",payboxParams);
// Déjà décodée par le framework
// String decoded = URLDecoder.decode(sign, this.CHARSET);
byte[] sigBytes = Base64.decode(signature.getBytes(this.CHARSET));
// lecture de la cle publique
PublicKey pubKey = this.getPubKey(pubKeyPath);
/**
* Dans le cas où le clé est au format .der
*
* PublicKey pubKey = this.getPubKeyDer(pubKeyPath);
*/
// verification signature
return this.verify(payboxParams.getBytes(), sigBytes, this.HASH_ENCRYPTION_ALGORITHM, pubKey);
}
示例11: getRememberedSerializedIdentity
import org.apache.shiro.codec.Base64; //导入依赖的package包/类
protected byte[] getRememberedSerializedIdentity(SubjectContext subjectContext) {
RequestWrapper requestWrapper = getRequestWrapper(subjectContext);
ResponseWrapper responseWrapper = getResponseWrapper(subjectContext);
String base64 = getCookie().readValue(requestWrapper, responseWrapper);
if (Cookie.DELETED_COOKIE_VALUE.equals(base64)) {
return null;
}
if (base64 != null) {
base64 = ensurePadding(base64);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Acquired Base64 encoded identity [" + base64 + "]");
}
byte[] decoded = Base64.decode(base64);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Base64 decoded byte array length: " + (decoded != null ? decoded.length : 0) + " bytes.");
}
return decoded;
} else {
//no cookie set - new site visitor?
return null;
}
}
示例12: rememberSerializedIdentity
import org.apache.shiro.codec.Base64; //导入依赖的package包/类
@Override
protected void rememberSerializedIdentity(Subject subject, byte[] serialized) {
String base64 = Base64.encodeToString(serialized);
CookieTemplate template = getCookie(); //the class attribute is really a template for the outgoing cookies
NewCookie cookie = new NewCookie(
template.getName(),
base64,
template.getPath(),
template.getDomain(),
template.getVersion(),
template.getComment(),
template.getMaxAge(),
template.getExpiry(),
template.isSecure(),
template.isHttpOnly());
Requests.removeProperty(RM_REMEMBER_COOKIE_KEY);
Requests.setProperty(ADD_REMEMBER_COOKIE_KEY, cookie);
}
示例13: getRememberedSerializedIdentity
import org.apache.shiro.codec.Base64; //导入依赖的package包/类
@Override
protected byte[] getRememberedSerializedIdentity(SubjectContext subjectContext) {
if (isIdentityRemoved()) {
return null;
}
Cookie cookie = Requests.getCookies().get(getCookie().getName());
//no cookie set - new site visitor?
if (cookie == null) return null;
String base64 = cookie.getValue();
if (Cookies.DELETED_COOKIE_VALUE.equals(base64)) return null;
if (base64 != null) {
base64 = ensurePadding(base64);
logger.trace("Acquired Base64 encoded identity [" + base64 + "]");
byte[] decoded = Base64.decode(base64);
logger.trace("Base64 decoded byte array length: " + (decoded != null ? decoded.length : 0) + " bytes.");
return decoded;
} else {
//no cookie set - new site visitor?
return null;
}
}
示例14: calculateRFC2104HMAC
import org.apache.shiro.codec.Base64; //导入依赖的package包/类
/**
* Computes RFC 2104-compliant HMAC signature.
* * @param data
* The data to be signed.
*
* @param key
* The signing key.
* @return
* The Base64-encoded RFC 2104-compliant HMAC signature.
* @throws java.security.SignatureException
* when signature generation fails
*/
public static String calculateRFC2104HMAC(String data, String key) throws java.security.SignatureException {
String result = null;
try {
Charset utf8ChartSet = Charset.forName("UTF-8");
// get an hmac_sha1 key from the raw key bytes
SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(utf8ChartSet), 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(utf8ChartSet));
// base64-encode the hmac
result = Base64.encodeToString(rawHmac);
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
}
return result;
}
示例15: getAccountByUsernameTest
import org.apache.shiro.codec.Base64; //导入依赖的package包/类
/**
* This test checks if the admin user exists in an initial database created by liquibase scripts.
*
* <p>The test also checks functionality of {@link AccountRepositoryImpl#getAccountByUsername(String)}
* method.
*
* <p>Admin user must be found.
*/
@Test
public void getAccountByUsernameTest() {
AccountEntity account = accountRepository.getAccountByUsername(entityManager, ADMIN_USERNAME);
// must be admin
assertNotNull(account);
assertNotNull(account.getId());
assertEquals(ADMIN_USERNAME, account.getUsername());
assertNotNull(account.getPassword());
assertNotNull(account.getPasswordSalt());
assertEquals(true, account.getIsCredentialsExpired());
// check password
byte[] salt = Base64.decode(account.getPasswordSalt());
String hashedPasswordBase64 = new SimpleHash(PersistenceRealm.HASH_ALGORITHM, ADMIN_PASSWORD, salt, PersistenceRealm.HASH_ITERATIONS).toBase64();
assertEquals(hashedPasswordBase64, account.getPassword());
}