Search in sources :

Example 96 with Base64

use of java.util.Base64 in project fuse-karaf by jboss-fuse.

the class MaskedPasswordHelper method createConfiguration.

@Override
public Map<String, String> createConfiguration(final Map<String, String> attributes) throws GeneralSecurityException, IOException {
    final Provider provider = ProviderHelper.provider(option(attributes, "provider", ProviderHelper.WILDFLY_PROVIDER));
    final String algorithm = option(attributes, "algorithm", DEFAULT_ALGORITHM);
    final PasswordFactory passwordFactory = PasswordFactory.getInstance(algorithm, provider);
    final String password = option(attributes, "password", null);
    final String salt = option(attributes, "salt", "");
    final String iterations = option(attributes, "iterations", "");
    final AlgorithmParameterSpec algorithmParameterSpec;
    if (salt.isEmpty() && iterations.isEmpty()) {
        algorithmParameterSpec = null;
    } else if (salt.isEmpty()) {
        algorithmParameterSpec = new IteratedPasswordAlgorithmSpec(parseInt(iterations));
    } else {
        final byte[] saltBytes = Base64.getDecoder().decode(salt);
        algorithmParameterSpec = new IteratedSaltedPasswordAlgorithmSpec(parseInt(iterations), saltBytes);
    }
    final EncryptablePasswordSpec keySpec = new EncryptablePasswordSpec(password.toCharArray(), algorithmParameterSpec);
    final MaskedPassword maskedPassword = passwordFactory.generatePassword(keySpec).castAs(MaskedPassword.class);
    final MaskedPasswordAlgorithmSpec maskedPasswordAlgorithmSpec = maskedPassword.getParameterSpec();
    final Map<String, String> configuration = new HashMap<>();
    final Encoder encoder = Base64.getEncoder();
    if (!DEFAULT_ALGORITHM.equals(algorithm)) {
        configuration.put(CREDENTIAL_STORE_PROTECTION_ALGORITHM, algorithm);
    }
    configuration.put(CREDENTIAL_STORE_PROTECTION, encoder.encodeToString(maskedPassword.getMaskedPasswordBytes()));
    final AlgorithmParameters algorithmParameters = AlgorithmParameters.getInstance(algorithm, provider);
    algorithmParameters.init(maskedPasswordAlgorithmSpec);
    final byte[] encoded = algorithmParameters.getEncoded();
    configuration.put(CREDENTIAL_STORE_PROTECTION_PARAMS, encoder.encodeToString(encoded));
    return configuration;
}
Also used : HashMap(java.util.HashMap) EncryptablePasswordSpec(org.wildfly.security.password.spec.EncryptablePasswordSpec) Provider(java.security.Provider) IteratedPasswordAlgorithmSpec(org.wildfly.security.password.spec.IteratedPasswordAlgorithmSpec) PasswordFactory(org.wildfly.security.password.PasswordFactory) Encoder(java.util.Base64.Encoder) IteratedSaltedPasswordAlgorithmSpec(org.wildfly.security.password.spec.IteratedSaltedPasswordAlgorithmSpec) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec) MaskedPassword(org.wildfly.security.password.interfaces.MaskedPassword) MaskedPasswordAlgorithmSpec(org.wildfly.security.password.spec.MaskedPasswordAlgorithmSpec) AlgorithmParameters(java.security.AlgorithmParameters)

Example 97 with Base64

use of java.util.Base64 in project fuse-karaf by jboss-fuse.

the class MaskedPasswordHelper method createCredentialSource.

@Override
public CredentialSource createCredentialSource(final Map<String, String> configuration) throws GeneralSecurityException, IOException {
    final String algorithmParamsBase64 = option(configuration, CREDENTIAL_STORE_PROTECTION_PARAMS, "");
    final Decoder decoder = Base64.getDecoder();
    final byte[] encodedAlgorithmParams = decoder.decode(algorithmParamsBase64);
    final String algorithm = option(configuration, CREDENTIAL_STORE_PROTECTION_ALGORITHM, DEFAULT_ALGORITHM);
    final Provider provider = ProviderHelper.provider(option(configuration, CREDENTIAL_STORE_PROTECTION_PROVIDER, ProviderHelper.WILDFLY_PROVIDER));
    final AlgorithmParameters algorithmParameters = AlgorithmParameters.getInstance(algorithm, provider);
    algorithmParameters.init(encodedAlgorithmParams);
    final MaskedPasswordAlgorithmSpec maskedPasswordAlgorithmSpec = algorithmParameters.getParameterSpec(MaskedPasswordAlgorithmSpec.class);
    final char[] initialKeyMaterial = maskedPasswordAlgorithmSpec.getInitialKeyMaterial();
    final int iterationCount = maskedPasswordAlgorithmSpec.getIterationCount();
    final byte[] salt = maskedPasswordAlgorithmSpec.getSalt();
    final String maskedPasswordBase64 = option(configuration, CREDENTIAL_STORE_PROTECTION, "");
    final byte[] maskedPasswordBytes = decoder.decode(maskedPasswordBase64);
    final MaskedPasswordSpec maskedPasswordSpec = new MaskedPasswordSpec(initialKeyMaterial, iterationCount, salt, maskedPasswordBytes);
    final PasswordFactory passwordFactory = PasswordFactory.getInstance(algorithm, provider);
    final Password maskedPassword = passwordFactory.generatePassword(maskedPasswordSpec);
    final PasswordFactory clearPasswordFactory = PasswordFactory.getInstance(ClearPassword.ALGORITHM_CLEAR, provider);
    final ClearPasswordSpec clearPasswordSpec = passwordFactory.getKeySpec(maskedPassword, ClearPasswordSpec.class);
    final Password password = clearPasswordFactory.generatePassword(clearPasswordSpec);
    final PasswordCredential passwordCredential = new PasswordCredential(password);
    return IdentityCredentials.NONE.withCredential(passwordCredential);
}
Also used : MaskedPasswordSpec(org.wildfly.security.password.spec.MaskedPasswordSpec) PasswordCredential(org.wildfly.security.credential.PasswordCredential) ClearPasswordSpec(org.wildfly.security.password.spec.ClearPasswordSpec) Decoder(java.util.Base64.Decoder) Provider(java.security.Provider) PasswordFactory(org.wildfly.security.password.PasswordFactory) MaskedPasswordAlgorithmSpec(org.wildfly.security.password.spec.MaskedPasswordAlgorithmSpec) AlgorithmParameters(java.security.AlgorithmParameters) MaskedPassword(org.wildfly.security.password.interfaces.MaskedPassword) Password(org.wildfly.security.password.Password) ClearPassword(org.wildfly.security.password.interfaces.ClearPassword)

Example 98 with Base64

use of java.util.Base64 in project mycore by MyCoRe-Org.

the class MCRSecureTokenV2 method buildHash.

private void buildHash() {
    String forHashing = Stream.concat(Stream.of(ipAddress, sharedSecret), // case of HttpServletRequest.getQueryString()==null
    Arrays.stream(queryParameters).filter(Objects::nonNull)).sorted().collect(Collectors.joining("&", contentPath + "?", ""));
    MessageDigest digest;
    try {
        digest = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException e) {
        // should never happen for 'SHA-256'
        throw new RuntimeException(e);
    }
    digest.update(URI.create(forHashing).toASCIIString().getBytes(StandardCharsets.US_ASCII));
    byte[] sha256 = digest.digest();
    hash = Base64.getEncoder().encodeToString(sha256).chars().map(x -> {
        switch(x) {
            case '+':
                return '-';
            case '/':
                return '_';
            default:
                return x;
        }
    }).collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString();
}
Also used : Objects(java.util.Objects) Arrays(java.util.Arrays) Base64(java.util.Base64) Stream(java.util.stream.Stream) MessageDigest(java.security.MessageDigest) URISyntaxException(java.net.URISyntaxException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) URI(java.net.URI) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) MessageDigest(java.security.MessageDigest)

Example 99 with Base64

use of java.util.Base64 in project fabric-sdk-java by hyperledger.

the class HFCAClient method reenroll.

/**
 * Re-Enroll the user with member service
 *
 * @param user User to be re-enrolled
 * @param req  Enrollment request with the following fields: hosts, profile, csr, label
 * @return enrollment
 * @throws EnrollmentException
 * @throws InvalidArgumentException
 */
public Enrollment reenroll(User user, EnrollmentRequest req) throws EnrollmentException, InvalidArgumentException {
    if (cryptoSuite == null) {
        throw new InvalidArgumentException("Crypto primitives not set.");
    }
    if (user == null) {
        throw new InvalidArgumentException("reenrollment user is missing");
    }
    if (user.getEnrollment() == null) {
        throw new InvalidArgumentException("reenrollment user is not a valid user object");
    }
    logger.debug(format("re-enroll user: %s, url: %s", user.getName(), url));
    try {
        setUpSSL();
        PublicKey publicKey = cryptoSuite.bytesToCertificate(user.getEnrollment().getCert().getBytes(StandardCharsets.UTF_8)).getPublicKey();
        KeyPair keypair = new KeyPair(publicKey, user.getEnrollment().getKey());
        // generate CSR
        String pem = cryptoSuite.generateCertificationRequest(user.getName(), keypair);
        // build request body
        req.setCSR(pem);
        if (caName != null && !caName.isEmpty()) {
            req.setCAName(caName);
        }
        String body = req.toJson();
        // build authentication header
        JsonObject result = httpPost(url + HFCA_REENROLL, body, user);
        // get new cert from response
        Base64.Decoder b64dec = Base64.getDecoder();
        String signedPem = new String(b64dec.decode(result.getString("Cert").getBytes(UTF_8)));
        logger.debug(format("[HFCAClient] re-enroll returned pem:[%s]", signedPem));
        logger.debug(format("reenroll user %s done.", user.getName()));
        return new HFCAEnrollment(keypair, signedPem);
    } catch (EnrollmentException ee) {
        logger.error(ee.getMessage(), ee);
        throw ee;
    } catch (Exception e) {
        EnrollmentException ee = new EnrollmentException(format("Failed to re-enroll user %s", user), e);
        logger.error(e.getMessage(), e);
        throw ee;
    }
}
Also used : KeyPair(java.security.KeyPair) InvalidArgumentException(org.hyperledger.fabric_ca.sdk.exception.InvalidArgumentException) Base64(java.util.Base64) EnrollmentException(org.hyperledger.fabric_ca.sdk.exception.EnrollmentException) PublicKey(java.security.PublicKey) JsonObject(javax.json.JsonObject) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) InvalidArgumentException(org.hyperledger.fabric_ca.sdk.exception.InvalidArgumentException) URISyntaxException(java.net.URISyntaxException) RegistrationException(org.hyperledger.fabric_ca.sdk.exception.RegistrationException) KeyStoreException(java.security.KeyStoreException) AffiliationException(org.hyperledger.fabric_ca.sdk.exception.AffiliationException) GenerateCRLException(org.hyperledger.fabric_ca.sdk.exception.GenerateCRLException) KeyManagementException(java.security.KeyManagementException) IdentityException(org.hyperledger.fabric_ca.sdk.exception.IdentityException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) EnrollmentException(org.hyperledger.fabric_ca.sdk.exception.EnrollmentException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) RevocationException(org.hyperledger.fabric_ca.sdk.exception.RevocationException) ParseException(org.apache.http.ParseException) MalformedURLException(java.net.MalformedURLException) InfoException(org.hyperledger.fabric_ca.sdk.exception.InfoException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) HTTPException(org.hyperledger.fabric_ca.sdk.exception.HTTPException)

Example 100 with Base64

use of java.util.Base64 in project ma-core-public by infiniteautomation.

the class JwtSignerVerifier method printToken.

public static String printToken(String token) {
    String[] parts = token.split("\\.");
    if (parts.length != 3) {
        return token;
    }
    Decoder base64Decoder = Base64.getDecoder();
    byte[] headerBytes = base64Decoder.decode(parts[0]);
    String header = new String(headerBytes, StandardCharsets.UTF_8);
    byte[] bodyBytes = base64Decoder.decode(parts[1]);
    String body = new String(bodyBytes, StandardCharsets.UTF_8);
    return String.format("{header: %s, body: %s}", header, body);
}
Also used : Decoder(java.util.Base64.Decoder)

Aggregations

Base64 (java.util.Base64)77 Decoder (java.util.Base64.Decoder)26 IOException (java.io.IOException)21 Test (org.junit.Test)20 Encoder (java.util.Base64.Encoder)18 List (java.util.List)17 StandardCharsets (java.nio.charset.StandardCharsets)15 Map (java.util.Map)15 HashMap (java.util.HashMap)14 Arrays (java.util.Arrays)12 Collectors (java.util.stream.Collectors)12 ArrayList (java.util.ArrayList)11 ByteArrayInputStream (java.io.ByteArrayInputStream)10 TimeUnit (java.util.concurrent.TimeUnit)10 File (java.io.File)9 Collections (java.util.Collections)9 Stream (java.util.stream.Stream)9 LoggerFactory (org.slf4j.LoggerFactory)9 CompletableFuture (java.util.concurrent.CompletableFuture)8 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)8