private byte[] createErrorMessage() { JsonObjectBuilder objectBuilder = Json.createObjectBuilder(); objectBuilder.add("status", "invalid_token"); Object asDiscoveryUrl = serverConfig.get(CONFIG_OPENID_CONFIGURATION_URL); if (asDiscoveryUrl != null) { objectBuilder.add(CONFIG_OPENID_CONFIGURATION_URL, asDiscoveryUrl.toString()); } return ByteIterator.ofBytes(objectBuilder.build().toString().getBytes()).base64Encode().asUtf8().drain(); } }
@Override public String createLogoutParameter(String sessionId) { try { Signature signature = Signature.getInstance(DEFAULT_SIGNATURE_ALGORITHM); signature.initSign(this.keyPair.getPrivate()); Base64.Encoder urlEncoder = Base64.getUrlEncoder(); return sessionId + "." + ByteIterator.ofBytes(urlEncoder.encode(ByteIterator.ofBytes(sessionId.getBytes(StandardCharsets.UTF_8)).sign(signature).drain())).asUtf8String().drainToString(); } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException e) { throw new IllegalStateException(e); } }
/** * Get a code point iterator for a UTF-8 encoded array. * * @param bytes the array * @param offs the array offset * @param len the number of characters to include * @return the code point iterator */ public static CodePointIterator ofUtf8Bytes(final byte[] bytes, final int offs, final int len) { if (len <= 0) { return EMPTY; } return ByteIterator.ofBytes(bytes, offs, len).asUtf8String(); }
public ScramFinalServerMessage parseFinalServerMessage(final byte[] messageBytes) throws AuthenticationMechanismException { final ByteIterator bi = ByteIterator.ofBytes(messageBytes); final byte[] sig; try { int c = bi.next(); if (c == 'e') { if (bi.next() == '=') { throw saslScram.scramServerRejectedAuthentication(ScramServerErrorCode.fromErrorString(bi.delimitedBy(',').asUtf8String().drainToString())); } throw saslScram.mechInvalidMessageReceived(); } else if (c == 'v' && bi.next() == '=') { sig = bi.delimitedBy(',').asUtf8String().base64Decode().drain(); } else { throw saslScram.mechInvalidMessageReceived(); } if (bi.hasNext()) { throw saslScram.mechInvalidMessageReceived(); } } catch (IllegalArgumentException e) { throw saslScram.mechInvalidMessageReceived(); } return new ScramFinalServerMessage(sig, messageBytes); }
passwordFactory = getPasswordFactory(ALGORITHM_DIGEST_MD5); try { byte[] hashed = ByteIterator.ofBytes(accountEntry.getPasswordRepresentation().getBytes(StandardCharsets.UTF_8)).asUtf8String().hexDecode().drain(); passwordSpec = new DigestPasswordSpec(accountEntry.getName(), loadedState.getRealmName(), hashed); } catch (DecodeException e) {
/** * Generate a new encoded nonce to send to the client. * * @param salt additional data to use when creating the overall signature for the nonce. * @return a new encoded nonce to send to the client. */ String generateNonce(byte[] salt) { try { MessageDigest messageDigest = MessageDigest.getInstance(algorithm); ByteBuffer byteBuffer = ByteBuffer.allocate(PREFIX_LENGTH + messageDigest.getDigestLength()); byteBuffer.putInt(nonceCounter.incrementAndGet()); byteBuffer.putLong(System.nanoTime()); byteBuffer.put(digest(byteBuffer.array(), 0, PREFIX_LENGTH, salt, messageDigest)); String nonce = ByteIterator.ofBytes(byteBuffer.array()).base64Encode().drainToString(); if (log.isTraceEnabled()) { String saltString = salt == null ? "null" : ByteIterator.ofBytes(salt).hexEncode().drainToString(); log.tracef("New nonce generated %s, using seed %s", nonce, saltString); } return nonce; } catch (GeneralSecurityException e) { throw new IllegalStateException(e); } }
ByteIterator bi = ByteIterator.ofBytes(response); try { if (bi.next() != 'c' || bi.next() != '=') { throw saslScram.mechInvalidMessageReceived(); ByteIterator ibi = bi.delimitedBy(',').asUtf8String().base64Decode(); char cbindFlag = (char) ibi.next(); final String bindingType = initialResponse.getBindingType(); final byte[] bindingData = initialResponse.getRawBindingData(); if (ibi.next() != '=') { throw saslScram.mechInvalidMessageReceived(); if (! bindingType.equals(ibi.delimitedBy(',').asUtf8String().drainToString())) { throw new ScramServerException(saslScram.mechChannelBindingTypeMismatch(), ScramServerErrorCode.UNSUPPORTED_CHANNEL_BINDING_TYPE); if (ibi.next() != ',') { throw saslScram.mechInvalidMessageReceived(); int c = ibi.next(); final String authorizationID; if (c == 'a') { if (ibi.next() != '=') { throw saslScram.mechInvalidClientMessage(); authorizationID = ibi.delimitedBy(',').asUtf8String().drainToString(); ibi.next(); // skip delimiter if (! authorizationID.equals(initialResponse.getAuthorizationId())) { throw saslScram.mechAuthorizationIdChanged();
public ScramInitialServerMessage parseInitialServerMessage(final ScramInitialClientMessage initialResponse, final byte[] bytes) throws AuthenticationMechanismException { final byte[] challenge = bytes.clone(); final ByteIterator bi = ByteIterator.ofBytes(challenge); final byte[] serverNonce; final byte[] salt; final int iterationCount; try { if (bi.peekNext() == 'e') { bi.next(); if (bi.next() == '=') { throw saslScram.scramServerRejectedAuthentication(ScramServerErrorCode.fromErrorString(bi.delimitedBy(',').asUtf8String().drainToString())); if (bi.next() != 'r' || bi.next() != '=') { throw saslScram.mechInvalidMessageReceived(); if (! bi.limitedTo(clientNonce.length).contentEquals(ByteIterator.ofBytes(clientNonce))) { throw saslScram.mechNoncesDoNotMatch(); serverNonce = bi.delimitedBy(',').drain(); bi.next(); // it's a , if (bi.next() != 's' || bi.next() != '=') { throw saslScram.mechInvalidMessageReceived(); salt = bi.delimitedBy(',').asUtf8String().base64Decode().drain(); bi.next(); // it's a , if (bi.next() != 'i' || bi.next() != '=') { throw saslScram.mechInvalidMessageReceived();
private String encodeUsingAlphabet(byte[] payload) { if (picketBoxCompatibility) { return picketBoxBased64Encode(payload); } else { CodePointIterator codePointIterator = isBase64(alphabet) ? ByteIterator.ofBytes(payload).base64Encode(getAlphabet64(alphabet), usePadding) : ByteIterator.ofBytes(payload).base32Encode(getAlphabet32(alphabet)); return codePointIterator.drainToString(); } }
static String base64UrlEncode(byte[] data) { return ByteIterator.ofBytes(data).base64Encode(BASE64_URL, false).drainToString(); }
MessageDigest messageDigest = MessageDigest.getInstance(algorithm); ByteIterator byteIterator = CodePointIterator.ofChars(nonce.toCharArray()).base64Decode(); byte[] nonceBytes = byteIterator.drain(); if (nonceBytes.length != PREFIX_LENGTH + messageDigest.getDigestLength()) { throw log.invalidNonceLength(); String saltString = salt == null ? "null" : ByteIterator.ofBytes(salt).hexEncode().drainToString(); log.tracef("Nonce %s rejected due to failed comparison using secret key with seed %s.", nonce, saltString);
private static byte[] modulusToByteArray(BigInteger modulus) { // As specified in https://tools.ietf.org/html/rfc7518#section-6.3.1, the extra zero-valued octet // needs to be omitted if present byte[] modulusByteArray = modulus.toByteArray(); if ((modulus.bitLength() % 8 == 0) && (modulusByteArray[0] == 0) && modulusByteArray.length > 1) { return ByteIterator.ofBytes(modulusByteArray, 1, modulusByteArray.length - 1).drain(); } else { return modulusByteArray; } }
public OAuth2InitialClientMessage parseInitialClientMessage(byte[] fromBytes) throws AuthenticationMechanismException { byte[] messageBytes = fromBytes.clone(); ByteIterator byteIterator = ByteIterator.ofBytes(fromBytes.clone()); try { final char cbindFlag = (char) byteIterator.next(); if (cbindFlag != 'n') { throw log.mechChannelBindingNotSupported(); } String authorizationID = null; if (byteIterator.next() == ',') { final int c = byteIterator.next(); if (c == 'a') { if (byteIterator.next() != '=') { throw log.mechInvalidClientMessage(); } authorizationID = byteIterator.delimitedBy(',').asUtf8String().drainToString(); if (byteIterator.next() != ',') { throw ElytronMessages.log.mechInvalidClientMessage(); } } } String auth = getValue("auth", byteIterator.asUtf8String().drainToString()); if (auth == null) { throw log.mechInvalidClientMessage(); } return new OAuth2InitialClientMessage(authorizationID, auth, messageBytes); } catch (NoSuchElementException ignored) { throw ElytronMessages.log.mechInvalidMessageReceived(); } }
/** * Create a DER decoder that will decode values from the given byte array. * * @param buf the byte array to decode */ public DERDecoder(byte[] buf) { this.bi = ByteIterator.ofBytes(buf); }
private String calculateNewAlias(String alias, Class<? extends Credential> credentialType, String algorithm, AlgorithmParameterSpec parameterSpec) throws CredentialStoreException { final StringBuilder b = new StringBuilder(64 + alias.length()); b.append(alias.toLowerCase(Locale.ROOT)); b.append('/'); b.append(credentialType.getSimpleName().toLowerCase(Locale.ROOT)); b.append('/'); if (algorithm != null) { b.append(algorithm.toLowerCase(Locale.ROOT)); b.append('/'); if (parameterSpec != null) try { final AlgorithmParameters algorithmParameters = AlgorithmParameters.getInstance(algorithm); algorithmParameters.init(parameterSpec); ByteIterator.ofBytes(algorithmParameters.getEncoded()).base32Encode(Base32Alphabet.LOWERCASE, false).drainTo(b); } catch (NoSuchAlgorithmException | InvalidParameterSpecException | IOException e) { throw log.cannotWriteCredentialToStore(e); } } else { b.append('/'); } return b.toString(); }
@Override public String verifyLogoutParameter(String parameter) { String[] parts = parameter.split("\\."); if (parts.length != 2) { throw new IllegalArgumentException(parameter); } try { String localSessionId = ByteIterator.ofBytes(parts[0].getBytes(StandardCharsets.UTF_8)).asUtf8String().drainToString(); Signature signature = Signature.getInstance(DEFAULT_SIGNATURE_ALGORITHM); signature.initVerify(this.keyPair.getPublic()); signature.update(localSessionId.getBytes(StandardCharsets.UTF_8)); Base64.Decoder urlDecoder = Base64.getUrlDecoder(); if (!ByteIterator.ofBytes(urlDecoder.decode(parts[1].getBytes(StandardCharsets.UTF_8))).verify(signature)) { throw log.httpMechSsoInvalidLogoutMessage(localSessionId); } return localSessionId; } catch (NoSuchAlgorithmException | InvalidKeyException e) { throw new IllegalStateException(e); } catch (SignatureException e) { throw new IllegalArgumentException(parameter, e); } }