Java Code Examples for org.keycloak.common.util.Base64#encodeBytes()

The following examples show how to use org.keycloak.common.util.Base64#encodeBytes() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TotpUtils.java    From keycloak with Apache License 2.0 8 votes vote down vote up
public static String qrCode(String totpSecret, RealmModel realm, UserModel user) {
    try {
        String keyUri = realm.getOTPPolicy().getKeyURI(realm, user, totpSecret);

        int width = 246;
        int height = 246;

        QRCodeWriter writer = new QRCodeWriter();
        final BitMatrix bitMatrix = writer.encode(keyUri, BarcodeFormat.QR_CODE, width, height);

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        MatrixToImageWriter.writeToStream(bitMatrix, "png", bos);
        bos.close();

        return Base64.encodeBytes(bos.toByteArray());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 2
Source File: WebAuthnCredentialProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Convert WebAuthn credential input to the model, which can be saved in the persistent storage (DB)
 *
 * @param input should be typically WebAuthnCredentialModelInput
 * @param userLabel label for the credential
 */
public WebAuthnCredentialModel getCredentialModelFromCredentialInput(CredentialInput input, String userLabel) {
    if (!supportsCredentialType(input.getType())) return null;

    WebAuthnCredentialModelInput webAuthnModel = (WebAuthnCredentialModelInput) input;

    String aaguid = webAuthnModel.getAttestedCredentialData().getAaguid().toString();
    String credentialId = Base64.encodeBytes(webAuthnModel.getAttestedCredentialData().getCredentialId());
    String credentialPublicKey = credentialPublicKeyConverter.convertToDatabaseColumn(webAuthnModel.getAttestedCredentialData().getCOSEKey());
    long counter = webAuthnModel.getCount();
    String attestationStatementFormat = webAuthnModel.getAttestationStatementFormat();

    WebAuthnCredentialModel model = WebAuthnCredentialModel.create(getType(), userLabel, aaguid, credentialId, null, credentialPublicKey, counter, attestationStatementFormat);

    model.setId(webAuthnModel.getCredentialDBId());

    return model;
}
 
Example 3
Source File: UserTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void createUserWithDeprecatedCredentialsFormat() throws IOException {
    UserRepresentation user = new UserRepresentation();
    user.setUsername("user_creds");
    user.setEmail("email@localhost");

    PasswordCredentialModel pcm = PasswordCredentialModel.createFromValues("my-algorithm", "theSalt".getBytes(), 22, "ABC");
    //CredentialRepresentation hashedPassword = ModelToRepresentation.toRepresentation(pcm);
    String deprecatedCredential = "{\n" +
            "      \"type\" : \"password\",\n" +
            "      \"hashedSaltedValue\" : \"" + pcm.getPasswordSecretData().getValue() + "\",\n" +
            "      \"salt\" : \"" + Base64.encodeBytes(pcm.getPasswordSecretData().getSalt()) + "\",\n" +
            "      \"hashIterations\" : " + pcm.getPasswordCredentialData().getHashIterations() + ",\n" +
            "      \"algorithm\" : \"" + pcm.getPasswordCredentialData().getAlgorithm() + "\"\n" +
            "    }";

    CredentialRepresentation deprecatedHashedPassword = JsonSerialization.readValue(deprecatedCredential, CredentialRepresentation.class);
    Assert.assertNotNull(deprecatedHashedPassword.getHashedSaltedValue());
    Assert.assertNull(deprecatedHashedPassword.getCredentialData());

    deprecatedHashedPassword.setCreatedDate(1001l);
    deprecatedHashedPassword.setUserLabel("deviceX");
    deprecatedHashedPassword.setType(CredentialRepresentation.PASSWORD);

    user.setCredentials(Arrays.asList(deprecatedHashedPassword));

    createUser(user, false);

    CredentialModel credentialHashed = fetchCredentials("user_creds");
    PasswordCredentialModel pcmh = PasswordCredentialModel.createFromCredentialModel(credentialHashed);
    assertNotNull("Expecting credential", credentialHashed);
    assertEquals("my-algorithm", pcmh.getPasswordCredentialData().getAlgorithm());
    assertEquals(Long.valueOf(1001), credentialHashed.getCreatedDate());
    assertEquals("deviceX", credentialHashed.getUserLabel());
    assertEquals(22, pcmh.getPasswordCredentialData().getHashIterations());
    assertEquals("ABC", pcmh.getPasswordSecretData().getValue());
    assertEquals("theSalt", new String(pcmh.getPasswordSecretData().getSalt()));
    assertEquals(CredentialRepresentation.PASSWORD, credentialHashed.getType());
}
 
Example 4
Source File: SerializationUtil.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static String encode(Object function) {
    try {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(os);
        oos.writeObject(function);
        oos.close();

        return Base64.encodeBytes(os.toByteArray());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 5
Source File: SerializationUtil.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static String encodeException(Throwable t) {
    try {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(os);
        oos.writeObject(t);
        oos.close();

        return "EXCEPTION:" + Base64.encodeBytes(os.toByteArray());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 6
Source File: TestingOIDCEndpointsApplicationResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/get-keys-as-base64")
public Map<String, String> getKeysAsBase64() {
    // It seems that PemUtils.decodePrivateKey, decodePublicKey can only treat RSA type keys, not EC type keys. Therefore, these are not used.
    String privateKeyPem = Base64.encodeBytes(clientData.getSigningKeyPair().getPrivate().getEncoded());
    String publicKeyPem = Base64.encodeBytes(clientData.getSigningKeyPair().getPublic().getEncoded());

    Map<String, String> res = new HashMap<>();
    res.put(PRIVATE_KEY, privateKeyPem);
    res.put(PUBLIC_KEY, publicKeyPem);
    return res;
}
 
Example 7
Source File: KcinitDriver.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected String generateEncryptionKey(String password) throws NoSuchAlgorithmException, InvalidKeySpecException {
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
    KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 100, 128);
    SecretKey tmp = factory.generateSecret(spec);
    byte[] aeskey = tmp.getEncoded();
    return Base64.encodeBytes(aeskey);
}
 
Example 8
Source File: SPNEGOAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected GSSContext establishContext() throws GSSException, IOException {
    GSSManager manager = GSSManager.getInstance();

    Oid[] supportedMechs = new Oid[] { KerberosConstants.KRB5_OID, KerberosConstants.SPNEGO_OID };
    GSSCredential gssCredential = manager.createCredential(null, GSSCredential.INDEFINITE_LIFETIME, supportedMechs, GSSCredential.ACCEPT_ONLY);
    GSSContext gssContext = manager.createContext(gssCredential);

    byte[] inputToken = Base64.decode(spnegoToken);
    byte[] respToken = gssContext.acceptSecContext(inputToken, 0, inputToken.length);
    responseToken = Base64.encodeBytes(respToken);

    return gssContext;
}
 
Example 9
Source File: BasicAuthHelper.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static String createHeader(String username, String password)
{
    StringBuffer buf = new StringBuffer(username);
    buf.append(':').append(password);
    try
    {
        return "Basic " + Base64.encodeBytes(buf.toString().getBytes("UTF-8"));
    }
    catch (UnsupportedEncodingException e)
    {
        throw new RuntimeException(e);
    }
}
 
Example 10
Source File: JWETest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testPassword() {
    byte[] salt = JWEUtils.generateSecret(8);
    String encodedSalt = Base64.encodeBytes(salt);
    String jwe = JWE.encryptUTF8("geheim", encodedSalt, PAYLOAD);
    String decodedContent = JWE.decryptUTF8("geheim", encodedSalt, jwe);
    Assert.assertEquals(PAYLOAD, decodedContent);
}
 
Example 11
Source File: Auth.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void addAuth(HttpRequest request) {
    String val = Base64.encodeBytes((username + ":" + password).getBytes());
    request.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + val);
}
 
Example 12
Source File: BasicAuthFilter.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void filter(ClientRequestContext requestContext) throws IOException {
    String pair = username + ":" + password;
    String authHeader = "Basic " + Base64.encodeBytes(pair.getBytes());
    requestContext.getHeaders().add(HttpHeaders.AUTHORIZATION, authHeader);
}
 
Example 13
Source File: SHAPasswordEncoder.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public String encode(String rawPassword) {
    MessageDigest messageDigest = getMessageDigest();

    byte[] digest = messageDigest.digest(rawPassword.getBytes(StandardCharsets.UTF_8));
    return Base64.encodeBytes(digest);
}
 
Example 14
Source File: ActionTokenKeyModel.java    From keycloak with Apache License 2.0 4 votes vote down vote up
default String serializeKey() {
    String userId = getUserId();
    String encodedUserId = userId == null ? "" : Base64.encodeBytes(userId.getBytes(StandardCharsets.UTF_8));
    return String.format("%s.%d.%s.%s", encodedUserId, getExpiration(), getActionVerificationNonce(), getActionId());
}
 
Example 15
Source File: CredentialModel.java    From keycloak with Apache License 2.0 4 votes vote down vote up
/**
 * @deprecated See {@link #getSalt()}
 */
@Deprecated
public void setSalt(byte[] salt) {
    String saltStr = salt == null ? null : Base64.encodeBytes(salt);
    writeProperty("salt", saltStr, true);
}