org.keycloak.common.util.Base64 Java Examples

The following examples show how to use org.keycloak.common.util.Base64. 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: GeneratedEcdsaKeyProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
protected KeyWrapper loadKey(RealmModel realm, ComponentModel model) {
       String privateEcdsaKeyBase64Encoded = model.getConfig().getFirst(GeneratedEcdsaKeyProviderFactory.ECDSA_PRIVATE_KEY_KEY);
       String publicEcdsaKeyBase64Encoded = model.getConfig().getFirst(GeneratedEcdsaKeyProviderFactory.ECDSA_PUBLIC_KEY_KEY);
       String ecInNistRep = model.getConfig().getFirst(GeneratedEcdsaKeyProviderFactory.ECDSA_ELLIPTIC_CURVE_KEY);

       try {
           PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(Base64.decode(privateEcdsaKeyBase64Encoded));
           KeyFactory kf = KeyFactory.getInstance("EC");
           PrivateKey decodedPrivateKey = kf.generatePrivate(privateKeySpec);

           X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(Base64.decode(publicEcdsaKeyBase64Encoded));
           PublicKey decodedPublicKey = kf.generatePublic(publicKeySpec);

           KeyPair keyPair = new KeyPair(decodedPublicKey, decodedPrivateKey);

           return createKeyWrapper(keyPair, ecInNistRep);
       } catch (Exception e) {
           logger.warnf("Exception at decodeEcdsaPublicKey. %s", e.toString());
           return null;
       }

   }
 
Example #3
Source File: JpaUserCredentialStore.java    From keycloak with Apache License 2.0 6 votes vote down vote up
CredentialModel toModel(CredentialEntity entity) {
    CredentialModel model = new CredentialModel();
    model.setId(entity.getId());
    model.setType(entity.getType());
    model.setCreatedDate(entity.getCreatedDate());
    model.setUserLabel(entity.getUserLabel());

    // Backwards compatibility - users from previous version still have "salt" in the DB filled.
    // We migrate it to new secretData format on-the-fly
    if (entity.getSalt() != null) {
        String newSecretData = entity.getSecretData().replace("__SALT__", Base64.encodeBytes(entity.getSalt()));
        entity.setSecretData(newSecretData);
        entity.setSalt(null);
    }

    model.setSecretData(entity.getSecretData());
    model.setCredentialData(entity.getCredentialData());
    return model;
}
 
Example #4
Source File: JpaUserFederatedStorageProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected CredentialModel toModel(FederatedUserCredentialEntity entity) {
    CredentialModel model = new CredentialModel();
    model.setId(entity.getId());
    model.setType(entity.getType());
    model.setCreatedDate(entity.getCreatedDate());
    model.setUserLabel(entity.getUserLabel());

    // Backwards compatibility - users from previous version still have "salt" in the DB filled.
    // We migrate it to new secretData format on-the-fly
    if (entity.getSalt() != null) {
        String newSecretData = entity.getSecretData().replace("__SALT__", Base64.encodeBytes(entity.getSalt()));
        entity.setSecretData(newSecretData);
        entity.setSalt(null);
    }

    model.setSecretData(entity.getSecretData());
    model.setCredentialData(entity.getCredentialData());
    return model;
}
 
Example #5
Source File: SAMLServletAdapterTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testDOMAssertion() throws Exception {
    assertSuccessfulLogin(employeeDomServletPage, bburkeUser, testRealmSAMLPostLoginPage, "principal=bburke");
    assertSuccessfullyLoggedIn(employeeDomServletPage, "principal=bburke");

    driver.navigate().to(employeeDomServletPage.getUriBuilder().clone().path("getAssertionFromDocument").build().toURL());
    waitForPageToLoad();
    String xml = driver.getPageSource();
    Assert.assertNotEquals("", xml);
    Document doc = DocumentUtil.getDocument(new StringReader(xml));
    String certBase64 = DocumentUtil.getElement(doc, new QName("http://www.w3.org/2000/09/xmldsig#", "X509Certificate")).getTextContent();
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    Certificate cert = cf.generateCertificate(new ByteArrayInputStream(Base64.decode(certBase64)));
    PublicKey pubkey = cert.getPublicKey();
    Assert.assertTrue(AssertionUtil.isSignatureValid(doc.getDocumentElement(), pubkey));

    employeeDomServletPage.logout();
    checkLoggedOut(employeeDomServletPage, testRealmSAMLPostLoginPage);
}
 
Example #6
Source File: KcinitDriver.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public JWE createJWE() {
    String key = getEncryptionKey();
    if (key == null) {
        throw new RuntimeException(KC_SESSION_KEY + " env var not set");
    }
    byte[] aesKey = null;
    try {
        aesKey = Base64.decode(key.getBytes(StandardCharsets.UTF_8));
    } catch (IOException e) {
        throw new RuntimeException("invalid " + KC_SESSION_KEY + "env var");
    }

    JWE jwe = new JWE();
    final SecretKey aesSecret = new SecretKeySpec(aesKey, "AES");
    jwe.getKeyStorage()
            .setDecryptionKey(aesSecret);
    return jwe;
}
 
Example #7
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 #8
Source File: LDAPPictureServlet.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType("image/jpeg");
    ServletOutputStream outputStream = resp.getOutputStream();

    KeycloakSecurityContext securityContext = (KeycloakSecurityContext) req.getAttribute(KeycloakSecurityContext.class.getName());
    IDToken idToken = securityContext.getIdToken();

    String profilePicture = idToken.getPicture();

    if (profilePicture != null) {
        byte[] decodedPicture = Base64.decode(profilePicture);
        outputStream.write(decodedPicture);
    }

    outputStream.flush();
}
 
Example #9
Source File: LDAPIdentityStore.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private BasicAttribute createBinaryBasicAttribute(String attrName, Set<String> attrValue) {
    BasicAttribute attr = new BasicAttribute(attrName);

    for (String value : attrValue) {
        if (value == null || value.trim().length() == 0) {
            value = LDAPConstants.EMPTY_ATTRIBUTE_VALUE;
        }

        try {
            byte[] bytes = Base64.decode(value);
            attr.add(bytes);
        } catch (IOException ioe) {
            logger.warnf("Wasn't able to Base64 decode the attribute value. Ignoring attribute update. Attribute: %s, Attribute value: %s", attrName, attrValue);
        }
    }

    return attr;
}
 
Example #10
Source File: SAMLParserTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testSaml20EncryptedAssertionWithNewlines() throws Exception {
    SAMLDocumentHolder holder = assertParsed("KEYCLOAK-4489-encrypted-assertion-with-newlines.xml", SAMLDocumentHolder.class);
    assertThat(holder.getSamlObject(), instanceOf(ResponseType.class));
    ResponseType resp = (ResponseType) holder.getSamlObject();
    assertThat(resp.getAssertions().size(), is(1));

    ResponseType.RTChoiceType rtChoiceType = resp.getAssertions().get(0);
    assertNull(rtChoiceType.getAssertion());
    assertNotNull(rtChoiceType.getEncryptedAssertion());

    PrivateKey privateKey = DerUtils.decodePrivateKey(Base64.decode(PRIVATE_KEY));
    AssertionUtil.decryptAssertion(holder, resp, privateKey);

    rtChoiceType = resp.getAssertions().get(0);
    assertNotNull(rtChoiceType.getAssertion());
    assertNull(rtChoiceType.getEncryptedAssertion());
}
 
Example #11
Source File: JWE.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static String encrypt(String password, String saltString, byte[] payload) {
    try {
        byte[] salt = Base64.decode(saltString);
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
        KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 100, 128);
        SecretKey tmp = factory.generateSecret(spec);
        SecretKey aesKey = new SecretKeySpec(tmp.getEncoded(), "AES");

        JWEHeader jweHeader = new JWEHeader(JWEConstants.A128KW, JWEConstants.A128CBC_HS256, null);
        JWE jwe = new JWE()
                .header(jweHeader)
                .content(payload);

        jwe.getKeyStorage()
                .setEncryptionKey(aesKey);

        return jwe.encodeJwe();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #12
Source File: JWE.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static byte[] decrypt(String password, String saltString, String encodedJwe) {
    try {
        byte[] salt = Base64.decode(saltString);
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
        KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 100, 128);
        SecretKey tmp = factory.generateSecret(spec);
        SecretKey aesKey = new SecretKeySpec(tmp.getEncoded(), "AES");

        JWE jwe = new JWE();
        jwe.getKeyStorage()
                .setDecryptionKey(aesKey);

        jwe.verifyAndDecodeJwe(encodedJwe);
        return jwe.getContent();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #13
Source File: DefaultActionTokenKey.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static DefaultActionTokenKey from(String serializedKey) {
    if (serializedKey == null) {
        return null;
    }
    String[] parsed = DOT.split(serializedKey, 4);
    if (parsed.length != 4) {
        return null;
    }

    String userId;
    try {
        userId = new String(Base64.decode(parsed[0]), StandardCharsets.UTF_8);
    } catch (IOException ex) {
        userId = parsed[0];
    }
    return new DefaultActionTokenKey(userId, parsed[3], Integer.parseInt(parsed[1]), UUID.fromString(parsed[2]));
}
 
Example #14
Source File: BasicAuthHelper.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static String[] parseHeader(String header)
{
    if (header.length() < 6) return null;
    String type = header.substring(0, 5);
    type = type.toLowerCase();
    if (!type.equalsIgnoreCase("Basic")) return null;
    String val = header.substring(6);
    try {
        val = new String(Base64.decode(val.getBytes()));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    int seperatorIndex = val.indexOf(":");
    if(seperatorIndex == -1) return null;
    String user = val.substring(0, seperatorIndex);
    String pw = val.substring(seperatorIndex + 1);
    return new String[]{user,pw};
}
 
Example #15
Source File: IdentityServiceRemoteUserMapperTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Utility method for creating a mocked Servlet request with basic auth.
 * 
 * @return The mocked request object
 */
@SuppressWarnings("unchecked")
private HttpServletRequest createMockBasicRequest()
{
    // Mock a request with the token in the Authorization header (if supplied)
    HttpServletRequest mockRequest = mock(HttpServletRequest.class);
    
    Vector<String> authHeaderValues = new Vector<>(1);
    String userPwd = TEST_USER_USERNAME + ":" + TEST_USER_USERNAME;
    authHeaderValues.add(BASIC_PREFIX + Base64.encodeBytes(userPwd.getBytes()));
    
    // NOTE: as getHeaders gets called twice provide two separate Enumeration objects so that
    // an empty result is not returned for the second invocation.
    when(mockRequest.getHeaders(AUTHORIZATION_HEADER)).thenReturn(authHeaderValues.elements(), 
                authHeaderValues.elements());
    
    return mockRequest;
}
 
Example #16
Source File: WebAuthnCredentialProvider.java    From keycloak-webauthn-authenticator with Apache License 2.0 6 votes vote down vote up
private void dumpWebAuthnCredentialModel(WebAuthnCredentialModel auth) {
    logger.debugv("  Context Credential Info::");
    String id = auth.getAuthenticatorId();
    AttestationStatement attrStatement = auth.getAttestationStatement();
    AttestedCredentialData attrCredData = auth.getAttestedCredentialData();
    WebAuthnAuthenticationContext context = auth.getAuthenticationContext();
    if (id != null) 
        logger.debugv("    Authenticator Id = {0}", id);
    if (attrStatement != null)
        logger.debugv("    Attestation Statement Format = {0}", attrStatement.getFormat());
    if (attrCredData != null) {
        CredentialPublicKey credPubKey = attrCredData.getCredentialPublicKey();
        byte[] keyId = credPubKey.getKeyId();
        logger.debugv("    AAGUID = {0}", attrCredData.getAaguid().toString());
        logger.debugv("    CREDENTIAL_ID = {0}", Base64.encodeBytes(attrCredData.getCredentialId()));
        if (keyId != null)
            logger.debugv("    CREDENTIAL_PUBLIC_KEY.key_id = {0}", Base64.encodeBytes(keyId));
        logger.debugv("    CREDENTIAL_PUBLIC_KEY.algorithm = {0}", credPubKey.getAlgorithm().name());
        logger.debugv("    CREDENTIAL_PUBLIC_KEY.key_type = {0}", credPubKey.getKeyType().name());
    }
    if (context != null) {
        // only set on Authentication
        logger.debugv("    Credential Id = {0}", Base64.encodeBytes(context.getCredentialId()));
    }
        
}
 
Example #17
Source File: HttpBasicAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private String[] getUsernameAndPassword(final HttpHeaders httpHeaders) {
    final List<String> authHeaders = httpHeaders.getRequestHeader(HttpHeaders.AUTHORIZATION);

    if (authHeaders == null || authHeaders.size() == 0) {
        return null;
    }

    String credentials = null;

    for (final String authHeader : authHeaders) {
        if (authHeader.startsWith(BASIC_PREFIX)) {
            final String[] split = authHeader.trim().split("\\s+");

            if (split.length != 2) return null;

            credentials = split[1];
        }
    }

    try {
        String val = new String(Base64.decode(credentials));
        int seperatorIndex = val.indexOf(":");
        if(seperatorIndex == -1) return new String[]{val};
        String user = val.substring(0, seperatorIndex);
        String pw = val.substring(seperatorIndex + 1);
        return new String[]{user,pw};
    } catch (final IOException e) {
        throw new RuntimeException("Failed to parse credentials.", e);
    }
}
 
Example #18
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 #19
Source File: GeneratedEcdsaKeyProviderFactory.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void generateKeys(ComponentModel model, String ecInNistRep) {
    KeyPair keyPair;
    try {
        keyPair = generateEcdsaKeyPair(convertECDomainParmNistRepToSecRep(ecInNistRep));
        model.put(ECDSA_PRIVATE_KEY_KEY, Base64.encodeBytes(keyPair.getPrivate().getEncoded()));
        model.put(ECDSA_PUBLIC_KEY_KEY, Base64.encodeBytes(keyPair.getPublic().getEncoded()));
        model.put(ECDSA_ELLIPTIC_CURVE_KEY, ecInNistRep);
    } catch (Throwable t) {
        throw new ComponentValidationException("Failed to generate ECDSA keys", t);
    }
}
 
Example #20
Source File: BasicAuthRequestAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public AuthOutcome authenticate(HttpFacade exchange)  {
    List<String> authHeaders = exchange.getRequest().getHeaders("Authorization");
    if (authHeaders == null || authHeaders.isEmpty()) {
        challenge = challengeResponse(exchange, OIDCAuthenticationError.Reason.NO_AUTHORIZATION_HEADER, null, null);
        return AuthOutcome.NOT_ATTEMPTED;
    }

    tokenString = null;
    for (String authHeader : authHeaders) {
        String[] split = authHeader.trim().split("\\s+");
        if (split.length != 2) continue;
        if (!split[0].equalsIgnoreCase("Basic")) continue;
        tokenString = split[1];
    }

    if (tokenString == null) {
        challenge = challengeResponse(exchange, OIDCAuthenticationError.Reason.INVALID_TOKEN, null, null);
        return AuthOutcome.NOT_ATTEMPTED;
    }

    AccessTokenResponse atr=null;        
    try {
        String userpw=new String(Base64.decode(tokenString));
        int seperatorIndex = userpw.indexOf(":");
        String user = userpw.substring(0, seperatorIndex);
        String pw = userpw.substring(seperatorIndex + 1);
        atr = getToken(user, pw);
        tokenString = atr.getToken();
    } catch (Exception e) {
        log.debug("Failed to obtain token", e);
        challenge = challengeResponse(exchange, OIDCAuthenticationError.Reason.INVALID_TOKEN, "no_token", e.getMessage());
        return AuthOutcome.FAILED;
    }

    return authenticateToken(exchange, atr.getToken());
}
 
Example #21
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 #22
Source File: CredentialModel.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * @deprecated Recommended to use PasswordCredentialModel.getSecretData().getSalt()
 */
@Deprecated
@JsonIgnore
public byte[] getSalt() {
    try {
        String saltStr = readString("salt", true);
        return saltStr == null ? null : Base64.decode(saltStr);
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
}
 
Example #23
Source File: AssertionUtilTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testSaml20Signed() throws Exception {
    
    X509Certificate decodeCertificate = DerUtils.decodeCertificate(new ByteArrayInputStream(Base64.decode(PUBLIC_CERT)));
    
    try (InputStream st = AssertionUtilTest.class.getResourceAsStream("saml20-signed-response.xml")) {
        Document document = DocumentUtil.getDocument(st);
        
        Element assertion = DocumentUtil.getDirectChildElement(document.getDocumentElement(), "urn:oasis:names:tc:SAML:2.0:assertion", "Assertion");
        
        assertTrue(AssertionUtil.isSignatureValid(assertion, decodeCertificate.getPublicKey()));
        
        // test manipulation of signature
        Element signatureElement = AssertionUtil.getSignature(assertion);
        byte[] validSignature = Base64.decode(signatureElement.getTextContent());
        
        // change the signature value slightly
        byte[] invalidSignature = Arrays.clone(validSignature);
        invalidSignature[0] ^= invalidSignature[0];
        signatureElement.setTextContent(Base64.encodeBytes(invalidSignature));
        
        // check that signature now is invalid
        assertFalse(AssertionUtil.isSignatureValid(document.getDocumentElement(), decodeCertificate.getPublicKey()));
        
        // restore valid signature, but remove Signature element, check that still invalid
        signatureElement.setTextContent(Base64.encodeBytes(validSignature));

        assertion.removeChild(signatureElement);
        assertFalse(AssertionUtil.isSignatureValid(document.getDocumentElement(), decodeCertificate.getPublicKey()));
    }
}
 
Example #24
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 #25
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 #26
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 #27
Source File: WebAuthnCredentialProvider.java    From keycloak-webauthn-authenticator with Apache License 2.0 5 votes vote down vote up
private List<WebAuthnCredentialModel> getWebAuthnCredentialModelList(RealmModel realm, UserModel user) {
    List<WebAuthnCredentialModel> auths = new ArrayList<>();
    for (CredentialModel credential : session.userCredentialManager().getStoredCredentialsByType(realm, user, WebAuthnCredentialModel.WEBAUTHN_CREDENTIAL_TYPE)) {
        WebAuthnCredentialModel auth = new WebAuthnCredentialModel();
        MultivaluedHashMap<String, String> attributes = credential.getConfig();

        AttestationStatementConverter attConv = new AttestationStatementConverter();
        AttestationStatement attrStatement = attConv.convertToEntityAttribute(attributes.getFirst(ATTESTATION_STATEMENT));
        auth.setAttestationStatement(attrStatement);

        AAGUID aaguid = new AAGUID(attributes.getFirst(AAGUID));

        byte[] credentialId = null;
        try {
            credentialId = Base64.decode(attributes.getFirst(CREDENTIAL_ID));
        } catch (IOException ioe) {
            // NOP
        }

        CredentialPublicKeyConverter credConv = new CredentialPublicKeyConverter();
        CredentialPublicKey pubKey = credConv.convertToEntityAttribute(attributes.getFirst(CREDENTIAL_PUBLIC_KEY));

        AttestedCredentialData attrCredData = new AttestedCredentialData(aaguid, credentialId, pubKey);

        auth.setAttestedCredentialData(attrCredData);

        long count = Long.parseLong(credential.getValue());
        auth.setCount(count);

        auth.setAuthenticatorId(credential.getId());

        auths.add(auth);
    }
    return auths;
}
 
Example #28
Source File: DeviceActivityManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/** Returns the device information associated with the given {@code userSession}.
 * 
 * 
 * @param userSession the userSession
 * @return the device information or null if no device is attached to the user session
 */
public static DeviceRepresentation getCurrentDevice(UserSessionModel userSession) {
    String deviceInfo = userSession.getNote(DEVICE_NOTE);

    if (deviceInfo == null) {
        return null;
    }

    try {
        return JsonSerialization.readValue(Base64.decode(deviceInfo), DeviceRepresentation.class);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #29
Source File: DeviceActivityManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Attaches a device to the given {@code userSession} where the device information is obtained from the {@link HttpHeaders#USER_AGENT} in the current
 * request, if available.
 * 
 * @param userSession the user session
 * @param session the keycloak session
 */
public static void attachDevice(UserSessionModel userSession, KeycloakSession session) {
    DeviceRepresentation current = getDeviceFromUserAgent(session);

    if (current != null) {
        try {
            userSession.setNote(DEVICE_NOTE, Base64.encodeBytes(JsonSerialization.writeValueAsBytes(current)));
        } catch (IOException cause) {
            throw new RuntimeException(cause);
        }
    }
}
 
Example #30
Source File: Pbkdf2PasswordHashProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private int keySize(PasswordCredentialModel credential) {
    try {
        byte[] bytes = Base64.decode(credential.getPasswordSecretData().getValue());
        return bytes.length * 8;
    } catch (IOException e) {
        throw new RuntimeException("Credential could not be decoded", e);
    }
}