Java Code Examples for org.keycloak.common.util.Base64#decode()
The following examples show how to use
org.keycloak.common.util.Base64#decode() .
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: GeneratedEcdsaKeyProvider.java From keycloak with Apache License 2.0 | 6 votes |
@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 2
Source File: BasicAuthHelper.java From keycloak with Apache License 2.0 | 6 votes |
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 3
Source File: JWE.java From keycloak with Apache License 2.0 | 6 votes |
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 4
Source File: JWE.java From keycloak with Apache License 2.0 | 6 votes |
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 5
Source File: LDAPIdentityStore.java From keycloak with Apache License 2.0 | 6 votes |
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 6
Source File: KcinitDriver.java From keycloak with Apache License 2.0 | 6 votes |
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: DefaultActionTokenKey.java From keycloak with Apache License 2.0 | 6 votes |
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 8
Source File: LDAPPictureServlet.java From keycloak with Apache License 2.0 | 6 votes |
@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: HttpBasicAuthenticator.java From keycloak with Apache License 2.0 | 5 votes |
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 10
Source File: WebAuthnCredentialProvider.java From keycloak-webauthn-authenticator with Apache License 2.0 | 5 votes |
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 11
Source File: BasicAuthRequestAuthenticator.java From keycloak with Apache License 2.0 | 5 votes |
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 12
Source File: CredentialModel.java From keycloak with Apache License 2.0 | 5 votes |
/** * @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 13
Source File: SPNEGOAuthenticator.java From keycloak with Apache License 2.0 | 5 votes |
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 14
Source File: PasswordSecretData.java From keycloak with Apache License 2.0 | 5 votes |
@JsonCreator public PasswordSecretData(@JsonProperty("value") String value, @JsonProperty("salt") String salt) throws IOException { if (salt == null || "__SALT__".equals(salt)) { this.value = value; this.salt = null; } else { this.value = value; this.salt = Base64.decode(salt); } }
Example 15
Source File: AssertionUtilTest.java From keycloak with Apache License 2.0 | 5 votes |
@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 16
Source File: SerializationUtil.java From keycloak with Apache License 2.0 | 5 votes |
public static Throwable decodeException(String result) { try { result = result.substring("EXCEPTION:".length()); byte[] bytes = Base64.decode(result); ByteArrayInputStream is = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(is); return (Throwable) ois.readObject(); } catch (Exception e) { throw new RuntimeException(e); } }
Example 17
Source File: Pbkdf2PasswordHashProvider.java From keycloak with Apache License 2.0 | 5 votes |
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); } }
Example 18
Source File: WebAuthnCredentialProvider.java From keycloak with Apache License 2.0 | 3 votes |
/** * Convert WebAuthnCredentialModel, which was usually retrieved from DB, to the CredentialInput, which contains data in the webauthn4j specific format */ private WebAuthnCredentialModelInput getCredentialInputFromCredentialModel(CredentialModel credential) { WebAuthnCredentialModel webAuthnCredential = getCredentialFromModel(credential); WebAuthnCredentialData credData = webAuthnCredential.getWebAuthnCredentialData(); WebAuthnCredentialModelInput auth = new WebAuthnCredentialModelInput(getType()); byte[] credentialId = null; try { credentialId = Base64.decode(credData.getCredentialId()); } catch (IOException ioe) { // NOP } AAGUID aaguid = new AAGUID(credData.getAaguid()); COSEKey pubKey = credentialPublicKeyConverter.convertToEntityAttribute(credData.getCredentialPublicKey()); AttestedCredentialData attrCredData = new AttestedCredentialData(aaguid, credentialId, pubKey); auth.setAttestedCredentialData(attrCredData); long count = credData.getCounter(); auth.setCount(count); auth.setCredentialDBId(credential.getId()); auth.setAttestationStatementFormat(credData.getAttestationStatementFormat()); return auth; }