Example usage for java.util Base64 getMimeDecoder

List of usage examples for java.util Base64 getMimeDecoder

Introduction

In this page you can find the example usage for java.util Base64 getMimeDecoder.

Prototype

public static Decoder getMimeDecoder() 

Source Link

Document

Returns a Decoder that decodes using the MIME type base64 decoding scheme.

Usage

From source file:ai.grakn.engine.tasks.TaskStateDeserializer.java

public static TaskState deserializeFromString(String data) {
    return (TaskState) SerializationUtils.deserialize(Base64.getMimeDecoder().decode(data));
}

From source file:io.undertow.server.security.SpnegoAuthenticationTestCase.java

@Test
public void testSpnegoSuccess() throws Exception {

    final TestHttpClient client = new TestHttpClient();
    HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL());
    HttpResponse result = client.execute(get);
    assertEquals(StatusCodes.UNAUTHORIZED, result.getStatusLine().getStatusCode());
    Header[] values = result.getHeaders(WWW_AUTHENTICATE.toString());
    String header = getAuthHeader(NEGOTIATE, values);
    assertEquals(NEGOTIATE.toString(), header);
    HttpClientUtils.readResponse(result);

    Subject clientSubject = login("jduke", "theduke".toCharArray());

    Subject.doAs(clientSubject, new PrivilegedExceptionAction<Void>() {

        @Override//w w  w.j  ava2  s .c  o  m
        public Void run() throws Exception {
            GSSManager gssManager = GSSManager.getInstance();
            GSSName serverName = gssManager
                    .createName("HTTP/" + DefaultServer.getDefaultServerAddress().getHostString(), null);

            GSSContext context = gssManager.createContext(serverName, SPNEGO, null,
                    GSSContext.DEFAULT_LIFETIME);

            byte[] token = new byte[0];

            boolean gotOur200 = false;
            while (!context.isEstablished()) {
                token = context.initSecContext(token, 0, token.length);

                if (token != null && token.length > 0) {
                    HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL());
                    get.addHeader(AUTHORIZATION.toString(),
                            NEGOTIATE + " " + FlexBase64.encodeString(token, false));
                    HttpResponse result = client.execute(get);

                    Header[] headers = result.getHeaders(WWW_AUTHENTICATE.toString());
                    if (headers.length > 0) {
                        String header = getAuthHeader(NEGOTIATE, headers);

                        byte[] headerBytes = header.getBytes(StandardCharsets.US_ASCII);
                        // FlexBase64.decode() returns byte buffer, which can contain backend array of greater size.
                        // when on such ByteBuffer is called array(), it returns the underlying byte array including the 0 bytes
                        // at the end, which makes the token invalid. => using Base64 mime decoder, which returnes directly properly sized byte[].
                        token = Base64.getMimeDecoder().decode(ArrayUtils.subarray(headerBytes,
                                NEGOTIATE.toString().length() + 1, headerBytes.length));
                    }

                    if (result.getStatusLine().getStatusCode() == StatusCodes.OK) {
                        Header[] values = result.getHeaders("ProcessedBy");
                        assertEquals(1, values.length);
                        assertEquals("ResponseHandler", values[0].getValue());
                        HttpClientUtils.readResponse(result);
                        assertSingleNotificationType(EventType.AUTHENTICATED);
                        gotOur200 = true;
                    } else if (result.getStatusLine().getStatusCode() == StatusCodes.UNAUTHORIZED) {
                        assertTrue("We did get a header.", headers.length > 0);

                        HttpClientUtils.readResponse(result);

                    } else {
                        fail(String.format("Unexpected status code %d",
                                result.getStatusLine().getStatusCode()));
                    }
                }
            }

            assertTrue(gotOur200);
            assertTrue(context.isEstablished());
            return null;
        }
    });
}

From source file:at.medevit.elexis.emediplan.core.internal.EMediplanServiceImpl.java

/**
 * Get the decoded String, from the zipped and Base64 encoded String. The first 9 characters
 * (CHMED header) are ignored.//from w w  w.j  a  va  2s  .c  om
 * 
 * @param encodedJson
 * @return
 */
protected String getDecodedJsonString(@NonNull String encodedJson) {
    String content = encodedJson.substring(9);
    byte[] zipped = Base64.getMimeDecoder().decode(content);
    StringBuilder sb = new StringBuilder();
    try {
        GZIPInputStream gzip = new GZIPInputStream(new ByteArrayInputStream(zipped));
        InputStreamReader reader = new InputStreamReader(gzip);
        BufferedReader in = new BufferedReader(reader);
        // Probably only single json line, but just to be sure ... 
        String read;
        while ((read = in.readLine()) != null) {
            sb.append(read);
        }
    } catch (IOException e) {
        LoggerFactory.getLogger(getClass()).error("Error decoding json", e);
        throw new IllegalStateException("Error decoding json", e);
    }
    return sb.toString();
}

From source file:ddf.security.samlp.SimpleSign.java

public boolean validateSignature(String sigAlg, String queryParamsToValidate, String encodedSignature,
        @Nullable String encodedPublicKey) throws SignatureException {
    if (encodedPublicKey == null) {
        LOGGER.warn(//from   w w w  .  ja v  a  2 s . co  m
                "Could not verify the signature of request because there was no signing certificate. Ensure that the IdP Metadata includes a signing certificate.");
        return false;
    }

    try {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X509");
        Certificate certificate = certificateFactory.generateCertificate(
                new ByteArrayInputStream(Base64.getMimeDecoder().decode(encodedPublicKey)));

        java.security.Signature sig;
        String jceSigAlg = JCEMapper.translateURItoJCEID(sigAlg);

        if (jceSigAlg == null) {
            throw new SignatureException(new NoSuchAlgorithmException(
                    String.format("The Signature Algorithm %s is not supported.", sigAlg)));
        }

        try {
            sig = java.security.Signature.getInstance(jceSigAlg);
        } catch (NoSuchAlgorithmException e) {
            throw new SignatureException(e);
        }

        sig.initVerify(certificate.getPublicKey());
        sig.update(queryParamsToValidate.getBytes(StandardCharsets.UTF_8));
        return sig.verify(Base64.getMimeDecoder().decode(encodedSignature));
    } catch (InvalidKeyException | CertificateException | java.security.SignatureException
            | IllegalArgumentException e) {
        throw new SignatureException(e);
    }
}

From source file:bean.RedSocial.java

/**
 * /*from w  w  w . ja v a2s.co  m*/
 * @param _nombre
 * @param _apellidos
 * @param _email
 * @param _dir_foto
 * @throws IOException 
 */
@Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = false, rollbackFor = transactionalBusinessException.CambiarPasswordException.class)
public void actualizarPerfilUsuario(String _nombre, String _apellidos, String _email, String _dir_foto)
        throws IOException {
    usuarioConectado = daoUsuario.obtenerUsuario(username);

    usuarioConectado.setNombre(_nombre);
    usuarioConectado.setApellidos(_apellidos);
    usuarioConectado.setEmail(_email);

    if (_dir_foto != null) {
        if (_dir_foto.contains("png")) {
            _dir_foto = _dir_foto.substring(22);
        } else {
            _dir_foto = _dir_foto.substring(23);
        }

        byte[] _fotoperfil = Base64.getMimeDecoder().decode(_dir_foto);
        usuarioConectado.setFotoperfil(_fotoperfil);

    }

    daoUsuario.actualizarUsuario(usuarioConectado);
}

From source file:bean.RedSocial.java

/**
 * /*www.jav a2  s .  co m*/
 * @param _nombre
 * @param _descripcion
 * @param _horario
 * @param _dir_foto
 * @param _cod_provincia
 * @throws IOException 
 */
@Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = false, rollbackFor = transactionalBusinessException.NuevaEscuelaException.class)
public void nuevaEscuela(String _nombre, String _descripcion, String _horario, String _dir_foto,
        Integer _cod_provincia) throws IOException {
    Provincia p = daoProvincia.obtenerProvincia(_cod_provincia);
    Escuela e = new Escuela(_nombre, p);

    e.setDescripcion(_descripcion);
    e.setHorario(_horario);

    if (_dir_foto != null) {
        if (_dir_foto.contains("png")) {
            _dir_foto = _dir_foto.substring(22);
        } else {
            _dir_foto = _dir_foto.substring(23);
        }

        byte[] _fotoescuela = Base64.getMimeDecoder().decode(_dir_foto);
        e.setFotoEscuela(_fotoescuela);
    }

    daoEscuela.guardarEscuela(e);

}

From source file:bean.RedSocial.java

/**
 * //from   ww  w  . j  a  v a  2  s .c om
 * @param _id_escuela
 * @param _orientacion
 * @param _nombre
 * @param _dir_foto
 * @throws IOException 
 */
@Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = false, rollbackFor = transactionalBusinessException.NuevoSectorException.class)
public void nuevoSector(Integer _id_escuela, String _orientacion, String _nombre, String _dir_foto)
        throws IOException {
    Orientacion o = daoOrientacion.obtenerOrientacion(Orientacion.orientacion.valueOf(_orientacion));

    Sector s = new Sector(_nombre, o);

    Escuela e = daoEscuela.obtenerEscuela(_id_escuela);

    s.setEscuela(e);
    s.setNombreSector(_nombre);

    if (_dir_foto != null) {
        if (_dir_foto.contains("png")) {
            _dir_foto = _dir_foto.substring(22);
        } else {
            _dir_foto = _dir_foto.substring(23);
        }

        byte[] _fotosector = Base64.getMimeDecoder().decode(_dir_foto);
        s.setFotoSector(_fotosector);
    }

    daoSector.guardarSector(s);

    e.getSectores().add(s);
    daoEscuela.actualizarEscuela(e);
}

From source file:org.codice.ddf.security.common.jaxrs.RestSecurity.java

public static String inflateBase64(String base64EncodedValue) throws IOException {
    byte[] deflatedValue = Base64.getMimeDecoder().decode(base64EncodedValue);
    InputStream is = new InflaterInputStream(new ByteArrayInputStream(deflatedValue),
            new Inflater(GZIP_COMPATIBLE));
    return IOUtils.toString(is, StandardCharsets.UTF_8.name());
}

From source file:org.codice.ddf.security.filter.login.LoginFilter.java

private void validateHolderOfKeyConfirmation(SamlAssertionWrapper assertion, X509Certificate[] x509Certs)
        throws SecurityServiceException {
    List<String> confirmationMethods = assertion.getConfirmationMethods();
    boolean hasHokMethod = false;
    for (String method : confirmationMethods) {
        if (OpenSAMLUtil.isMethodHolderOfKey(method)) {
            hasHokMethod = true;//w  w  w  .j av  a 2  s .com
        }
    }

    if (hasHokMethod) {
        if (x509Certs != null && x509Certs.length > 0) {
            List<SubjectConfirmation> subjectConfirmations = assertion.getSaml2().getSubject()
                    .getSubjectConfirmations();
            for (SubjectConfirmation subjectConfirmation : subjectConfirmations) {
                if (OpenSAMLUtil.isMethodHolderOfKey(subjectConfirmation.getMethod())) {
                    Element dom = subjectConfirmation.getSubjectConfirmationData().getDOM();
                    Node keyInfo = dom.getFirstChild();
                    Node x509Data = keyInfo.getFirstChild();
                    Node dataNode = x509Data.getFirstChild();
                    Node dataText = dataNode.getFirstChild();

                    X509Certificate tlsCertificate = x509Certs[0];
                    if (dataNode.getLocalName().equals("X509Certificate")) {
                        String textContent = dataText.getTextContent();
                        byte[] byteValue = Base64.getMimeDecoder().decode(textContent);
                        try {
                            CertificateFactory cf = CertificateFactory.getInstance("X.509");
                            X509Certificate cert = (X509Certificate) cf
                                    .generateCertificate(new ByteArrayInputStream(byteValue));
                            //check that the certificate is still valid
                            cert.checkValidity();

                            //HoK spec section 2.5:
                            //relying party MUST ensure that the certificate bound to the assertion matches the X.509 certificate in its possession.
                            //Matching is done by comparing the base64-decoded certificates, or the hash values of the base64-decoded certificates, byte-for-byte.
                            //if the certs aren't the same, verify
                            if (!tlsCertificate.equals(cert)) {
                                //verify that the cert was signed by the same private key as the TLS cert
                                cert.verify(tlsCertificate.getPublicKey());
                            }
                        } catch (CertificateException | NoSuchAlgorithmException | InvalidKeyException
                                | SignatureException | NoSuchProviderException e) {
                            throw new SecurityServiceException(
                                    "Unable to validate Holder of Key assertion with certificate.");
                        }

                    } else if (dataNode.getLocalName().equals("X509SubjectName")) {
                        String textContent = dataText.getTextContent();
                        //HoK spec section 2.5:
                        //relying party MUST ensure that the subject distinguished name (DN) bound to the assertion matches the DN bound to the X.509 certificate.
                        //If, however, the relying party does not trust the certificate issuer to issue such a DN, the attesting entity is not confirmed and the relying party SHOULD disregard the assertion.
                        if (!tlsCertificate.getSubjectDN().getName().equals(textContent)) {
                            throw new SecurityServiceException(
                                    "Unable to validate Holder of Key assertion with subject DN.");
                        }

                    } else if (dataNode.getLocalName().equals("X509IssuerSerial")) {
                        //we have no way to support this confirmation type so we have to throw an error
                        throw new SecurityServiceException(
                                "Unable to validate Holder of Key assertion with issuer serial. NOT SUPPORTED");
                    } else if (dataNode.getLocalName().equals("X509SKI")) {
                        String textContent = dataText.getTextContent();
                        byte[] tlsSKI = tlsCertificate.getExtensionValue("2.5.29.14");
                        byte[] assertionSKI = Base64.getMimeDecoder().decode(textContent);
                        if (tlsSKI != null && tlsSKI.length > 0) {
                            ASN1OctetString tlsOs = ASN1OctetString.getInstance(tlsSKI);
                            ASN1OctetString assertionOs = ASN1OctetString.getInstance(assertionSKI);
                            SubjectKeyIdentifier tlsSubjectKeyIdentifier = SubjectKeyIdentifier
                                    .getInstance(tlsOs.getOctets());
                            SubjectKeyIdentifier assertSubjectKeyIdentifier = SubjectKeyIdentifier
                                    .getInstance(assertionOs.getOctets());
                            //HoK spec section 2.5:
                            //relying party MUST ensure that the value bound to the assertion matches the Subject Key Identifier (SKI) extension bound to the X.509 certificate.
                            //Matching is done by comparing the base64-decoded SKI values byte-for-byte. If the X.509 certificate does not contain an SKI extension,
                            //the attesting entity is not confirmed and the relying party SHOULD disregard the assertion.
                            if (!Arrays.equals(tlsSubjectKeyIdentifier.getKeyIdentifier(),
                                    assertSubjectKeyIdentifier.getKeyIdentifier())) {
                                throw new SecurityServiceException(
                                        "Unable to validate Holder of Key assertion with subject key identifier.");
                            }
                        } else {
                            throw new SecurityServiceException(
                                    "Unable to validate Holder of Key assertion with subject key identifier.");
                        }
                    }
                }
            }
        } else {
            throw new SecurityServiceException("Holder of Key assertion, must be used with 2-way TLS.");
        }
    }
}

From source file:org.codice.ddf.security.idp.binding.post.PostRequestDecoder.java

@Override
public AuthnRequest decodeRequest(String samlRequest) {
    LOGGER.debug("Creating AuthnRequest object from SAMLRequest string.");
    if (StringUtils.isEmpty(samlRequest)) {
        throw new IllegalArgumentException("Missing SAMLRequest on IdP request.");
    }/*from  w w w .  j a  v a2s .c o  m*/
    String decodedRequest = new String(Base64.getMimeDecoder().decode(samlRequest), StandardCharsets.UTF_8);
    ByteArrayInputStream tokenStream = new ByteArrayInputStream(
            decodedRequest.getBytes(StandardCharsets.UTF_8));
    Document authnDoc;
    try {
        authnDoc = StaxUtils.read(new InputStreamReader(tokenStream, "UTF-8"));
    } catch (Exception ex) {
        throw new IllegalArgumentException("Unable to read SAMLRequest as XML.");
    }
    XMLObject authnXmlObj;
    try {
        authnXmlObj = OpenSAMLUtil.fromDom(authnDoc.getDocumentElement());
    } catch (WSSecurityException ex) {
        throw new IllegalArgumentException("Unable to convert AuthnRequest document to XMLObject.");
    }
    if (!(authnXmlObj instanceof AuthnRequest)) {
        throw new IllegalArgumentException("SAMLRequest object is not AuthnRequest.");
    }
    LOGGER.debug("Created AuthnRequest object successfully.");
    return (AuthnRequest) authnXmlObj;
}