Search in sources :

Example 36 with Decoder

use of java.util.Base64.Decoder in project j2objc by google.

the class Base64Test method testEncoder_encodeArrayToArray.

/**
 * Tests {@link Decoder#decode(byte[], byte[])} for correctness.
 */
public void testEncoder_encodeArrayToArray() {
    Encoder encoder = Base64.getEncoder();
    // Empty input
    assertEquals(0, encoder.encode(new byte[0], new byte[0]));
    // Test data for non-empty input
    byte[] input = "abcefghi".getBytes(US_ASCII);
    String expectedString = "YWJjZWZnaGk=";
    byte[] encodedBytes = expectedString.getBytes(US_ASCII);
    // Non-empty input: output array too short
    byte[] tooShort = new byte[encodedBytes.length - 1];
    try {
        encoder.encode(input, tooShort);
        fail();
    } catch (IllegalArgumentException expected) {
    }
    // Non-empty input: output array longer than required
    byte[] tooLong = new byte[encodedBytes.length + 1];
    int tooLongBytesEncoded = encoder.encode(input, tooLong);
    assertEquals(encodedBytes.length, tooLongBytesEncoded);
    assertEquals(0, tooLong[tooLong.length - 1]);
    assertArrayPrefixEquals(tooLong, encodedBytes.length, encodedBytes);
    // Non-empty input: output array has exact minimum required size
    byte[] justRight = new byte[encodedBytes.length];
    int justRightBytesEncoded = encoder.encode(input, justRight);
    assertEquals(encodedBytes.length, justRightBytesEncoded);
    assertArrayEquals(encodedBytes, justRight);
}
Also used : Encoder(java.util.Base64.Encoder)

Example 37 with Decoder

use of java.util.Base64.Decoder 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 38 with Decoder

use of java.util.Base64.Decoder 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 39 with Decoder

use of java.util.Base64.Decoder 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)

Example 40 with Decoder

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

the class JwtSignerVerifier method keysToKeyPair.

public static KeyPair keysToKeyPair(String publicKeyStr, String privateKeyStr) {
    Decoder base64Decoder = Base64.getDecoder();
    byte[] publicBase64 = base64Decoder.decode(publicKeyStr);
    byte[] privateBase64 = base64Decoder.decode(privateKeyStr);
    try {
        KeyFactory kf = KeyFactory.getInstance("ECDSA", BouncyCastleProvider.PROVIDER_NAME);
        PublicKey publicKey = kf.generatePublic(new X509EncodedKeySpec(publicBase64));
        PrivateKey privateKey = kf.generatePrivate(new PKCS8EncodedKeySpec(privateBase64));
        return new KeyPair(publicKey, privateKey);
    } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidKeySpecException e) {
        throw new ShouldNeverHappenException(e);
    }
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) PublicKey(java.security.PublicKey) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Decoder(java.util.Base64.Decoder) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) ShouldNeverHappenException(com.serotonin.ShouldNeverHappenException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) NoSuchProviderException(java.security.NoSuchProviderException) KeyFactory(java.security.KeyFactory)

Aggregations

Decoder (java.util.Base64.Decoder)27 Base64 (java.util.Base64)21 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)7 Encoder (java.util.Base64.Encoder)7 KeyFactory (java.security.KeyFactory)6 X509EncodedKeySpec (java.security.spec.X509EncodedKeySpec)6 IOException (java.io.IOException)5 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)5 JOSEObjectType (com.nimbusds.jose.JOSEObjectType)4 JWSAlgorithm (com.nimbusds.jose.JWSAlgorithm)4 JWSHeader (com.nimbusds.jose.JWSHeader)4 JWSSigner (com.nimbusds.jose.JWSSigner)4 MACSigner (com.nimbusds.jose.crypto.MACSigner)4 JWKSource (com.nimbusds.jose.jwk.source.JWKSource)4 DefaultJOSEObjectTypeVerifier (com.nimbusds.jose.proc.DefaultJOSEObjectTypeVerifier)4 JWSKeySelector (com.nimbusds.jose.proc.JWSKeySelector)4 JWSVerificationKeySelector (com.nimbusds.jose.proc.JWSVerificationKeySelector)4 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)4 SignedJWT (com.nimbusds.jwt.SignedJWT)4 RSAPublicKey (java.security.interfaces.RSAPublicKey)4