Example usage for org.bouncycastle.util.encoders Base64 encode

List of usage examples for org.bouncycastle.util.encoders Base64 encode

Introduction

In this page you can find the example usage for org.bouncycastle.util.encoders Base64 encode.

Prototype

public static byte[] encode(byte[] data) 

Source Link

Document

encode the input data producing a base 64 encoded byte array.

Usage

From source file:org.tastefuljava.minica.SSHEncoding.java

License:Open Source License

public static String encode(PublicKey key, String comment) {
    try {//from   ww  w.  j a  v  a 2 s. c  o  m
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        String type;
        if (key instanceof RSAPublicKey) {
            type = "ssh-rsa";
            writeBytes(type.getBytes("US-ASCII"), baos);
            writeRSAKey((RSAPublicKey) key, baos);
        } else if (key instanceof DSAPublicKey) {
            type = "ssh-dss";
            writeBytes(type.getBytes("US-ASCII"), baos);
            writeDSAKey((DSAPublicKey) key, baos);
        } else {
            throw new RuntimeException("Unsupported key type");
        }
        StringBuilder buf = new StringBuilder();
        byte[] bytes = Base64.encode(baos.toByteArray());
        buf.append(type);
        buf.append(' ');
        buf.append(new String(bytes, "US-ASCII"));
        if (comment != null) {
            buf.append(' ');
            buf.append(comment);
        }
        return buf.toString();
    } catch (IOException ex) {
        // very unlikely
        LOG.log(Level.SEVERE, "Error encoding key", ex);
        throw new RuntimeException(ex.getMessage());
    }
}

From source file:org.teragrid.portal.filebrowser.applet.util.proxy.MyProxyLogon.java

License:Open Source License

private static void printB64(byte[] data, PrintStream out) {
    byte[] b64data;

    b64data = Base64.encode(data);
    for (int i = 0; i < b64data.length; i += b64linelen) {
        if ((b64data.length - i) > b64linelen) {
            out.write(b64data, i, b64linelen);
        } else {/*w  w  w . j ava 2s.co m*/
            out.write(b64data, i, b64data.length - i);
        }
        out.println();
    }
}

From source file:org.trpr.platform.core.impl.security.HashGeneratorImpl.java

License:Apache License

/**
 * Interface method implementation.//  ww  w. j av a  2  s .com
 * @see HashGenerator#generateHashAsBase64String(byte[])
 */
public String generateHashAsBase64String(byte[] data) throws SecurityException {
    return new String(Base64.encode(generateHash(data)));
}

From source file:org.trpr.platform.core.impl.security.HashGeneratorImpl.java

License:Apache License

/**
 * Interface method implementation.// w w  w.  j  av a 2  s.c  o m
 * @see HashGenerator#generateHashAsBase64String(byte[], byte[])
 */
public String generateHashAsBase64String(byte[] data, byte[] salt) throws SecurityException {
    return new String(Base64.encode(generateHash(data, salt)));
}

From source file:org.viafirma.nucleo.firma.imp.FirmaAppletBridgeImp.java

License:Open Source License

/***************************************************************************
 * Para solicitar el certificado redirecciona al cliente a una pgina que
 * contiene un Applet que solicita al usuario su certificado.
 * //  w  w w  .j  a  va 2s.  c  o m
 * @see org.viafirma.nucleo.autenticacion.AutenticacionBridge#generarSolicitudCertificado(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 */
public void generarSolicitudFirma(Documento documento, HttpServletRequest request,
        HttpServletResponse response) {
    log.debug("Iniciando solicitud de firma de documeto");
    // almaceno el identificador de sessin( posteriormente se utiliza para
    // cachear los diferentes certificados)
    request.setAttribute(Nucleo.SESSION_ID, request.getSession().getId());
    request.setAttribute(DOCUMENT_TO_SIGN_ID, documento.getId());

    // Procesamos del formato Xades
    preprocessXadesEpesEnveloped(documento, request);

    String shaHash = new String(
            Base64.encode(org.apache.commons.codec.digest.DigestUtils.sha(documento.getDatos())));
    StringBuffer sb = new StringBuffer();
    sb.append("<?xml version=\"1.0\" encoding=\"utf8\" ?>");
    sb.append("<attachments>");
    sb.append("<attachment>");
    sb.append("<title>").append(documento.getNombre()).append("</title>");
    sb.append("<path>").append(getRequestDownload(request, documento)).append("</path>");
    sb.append("<mimeType>").append(documento.getTipo().getMimetype()).append("</mimeType>");
    sb.append("<size>").append(documento.getSize()).append("</size>");
    sb.append("<hashValue>").append(shaHash).append("</hashValue>");
    if (TypeFormatSign.XADES_EPES_ENVELOPED.equals(documento.getTypeFormatSign())) {
        throw new UnsupportedOperationException(
                "Esta operacin no esta soportada o implementada en la versin Viafirma GPL/Estandar");
    }
    // if (isOptional) {
    // sb.append("<optional/>");
    // }
    sb.append("</attachment>");
    sb.append("</attachments>");

    // meto en request el parametro attachments
    request.setAttribute("attachments", new String(Base64.encode(sb.toString().getBytes())));
    try {
        request.setAttribute("signtext",
                new String(Base64.encode(("Firma del documento: " + documento.getNombre()).getBytes("UTF-8"))));
    } catch (UnsupportedEncodingException e) {
        log.error("No se puede codificar el texto para ser firmado.", e);
    }

    FaceletsUtil.forward(request, response, URI_FIRMA);
}

From source file:org.viafirma.nucleo.firma.imp.FirmaOpenocesAppletBridgeImp.java

License:Open Source License

/***************************************************************************
 * Para solicitar el certificado redirecciona al cliente a una pgina que
 * contiene un Applet que solicita al usuario su certificado.
 * /*  ww w  .java  2 s  . c om*/
 * @see org.viafirma.nucleo.autenticacion.AutenticacionBridge#generarSolicitudCertificado(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 */
public void generarSolicitudFirma(Documento documento, HttpServletRequest request,
        HttpServletResponse response) {
    log.debug("Iniciando solicitud de firma de documeto");
    // almaceno el identificador de sessin( posteriormente se utiliza para
    // cachear los diferentes certificados)
    request.setAttribute(Nucleo.SESSION_ID, request.getSession().getId());
    request.setAttribute(DOCUMENT_TO_SIGN_ID, documento.getId());

    // Procesamos del formato Xades
    //preprocessXadesEpesEnveloped(documento, request);

    String shaHash = new String(
            Base64.encode(org.apache.commons.codec.digest.DigestUtils.sha(documento.getDatos())));
    StringBuffer sb = new StringBuffer();
    sb.append("<?xml version=\"1.0\" encoding=\"utf8\" ?>");
    sb.append("<attachments>");
    sb.append("<attachment>");
    sb.append("<title>").append(documento.getNombre()).append("</title>");
    sb.append("<path>").append(getRequestDownload(request, documento)).append("</path>");
    sb.append("<mimeType>").append(documento.getTipo().getMimetype()).append("</mimeType>");
    sb.append("<size>").append(documento.getSize()).append("</size>");
    sb.append("<hashValue>").append(shaHash).append("</hashValue>");
    if (TypeFormatSign.XADES_EPES_ENVELOPED.equals(documento.getTypeFormatSign())) {
        sb.append("<signTime>").append(getSignTime()).append("</signTime>");
    }
    // if (isOptional) {
    // sb.append("<optional/>");
    // }
    sb.append("</attachment>");
    sb.append("</attachments>");

    // meto en request el parametro attachments
    request.setAttribute("attachments", new String(Base64.encode(sb.toString().getBytes())));
    try {
        request.setAttribute("signtext",
                new String(Base64.encode(("Firma del documento: " + documento.getNombre()).getBytes("UTF-8"))));
    } catch (UnsupportedEncodingException e) {
        log.error("No se puede codificar el texto para ser firmado.", e);
    }

    FaceletsUtil.forward(request, response, URI_FIRMA);
}

From source file:org.votingsystem.signature.util.AESParams.java

License:Open Source License

public Map<String, String> toMap() throws UnsupportedEncodingException {
    Map jsonObject = new HashMap<>();
    jsonObject.put("key", new String(Base64.encode(key.getEncoded()), "UTF-8"));
    jsonObject.put("iv", new String(Base64.encode(iv.getIV()), "UTF-8"));
    return jsonObject;
}

From source file:org.vpac.grix.model.certificate.CertificationRequest.java

License:Open Source License

/**
 * creates a encoded representation of the certification request.
 * //from   w w w.  j a va  2s.  c  o m
 * @return the certification request.
 */
public String getEncodedRequest() {

    String request_string = null;
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    // stolen from jglobus.jar:

    // nothing in it
    DERSet derset = new DERSet();
    PublicKey pubkey = this.keypair.getPublicKey();
    PrivateKey privkey = this.keypair.getPrivateKey().getPrivateKey();

    PKCS10CertificationRequest request = null;

    try {
        // using the already implemented .getEncoded() function of
        // PKCS10CertificationRequest
        request = new PKCS10CertificationRequest(this.signatureAlgorithm, this.dn, pubkey, derset, privkey);

        PEMUtils.writeBase64(out, "-----BEGIN CERTIFICATE REQUEST-----", Base64.encode(request.getEncoded()),
                "-----END CERTIFICATE REQUEST-----");

        request_string = out.toString();
        out.close();
    } catch (Exception e) {
        // TODO throw new SecurityProviderException("Could not write
        // certification request to file.");
        // e.printStackTrace();
        myLogger.error(e);
    }

    return request_string;
}

From source file:org.vpac.grix.model.certificate.PKCS12Certificate.java

License:Open Source License

/**
 * Parses a p12 file and loads the first certificate and private key into
 * this object. Use this constructor if you want to export pem files out of
 * a .p12 file./*from w ww  .  ja  v a2s .  c o  m*/
 * 
 * @param p12File
 * @param passphrase
 * @throws IOException
 * @throws GeneralSecurityException
 */
public PKCS12Certificate(File p12File, char[] passphrase) throws IOException, GeneralSecurityException {

    KeyStore ks = KeyStore.getInstance("PKCS12");
    FileInputStream pkcs12File = new FileInputStream(p12File);
    ks.load(pkcs12File, passphrase);
    pkcs12File.close();

    Enumeration<String> aliases = ks.aliases();
    // this takes the first alias
    alias = aliases.nextElement();

    // while (aliases.hasMoreElements()){
    // System.out.println("Alias: "+aliases.nextElement());
    // }

    privateKey = new BouncyCastleOpenSSLKey((PrivateKey) ks.getKey(alias, passphrase));
    if (privateKey == null) {
        throw new GeneralSecurityException("No private key found in keystore.");
    }
    // System.out.println(privateKey.getFormat());

    java.security.cert.Certificate javaCertificate = ks.getCertificate(alias);
    // System.out.println(certificate.getPublicKey().getAlgorithm());
    if (javaCertificate == null) {
        Arrays.fill(passphrase, 'x');
        throw new GeneralSecurityException("No certificate found in keystore");
    }

    byte[] cert = null;

    cert = javaCertificate.getEncoded();

    cert = Base64.encode(cert);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    PEMUtils.writeBase64(out, Certificate.PEM_HEADER, cert, Certificate.PEM_FOOTER);
    out.close();

    certificate = new Certificate(out.toString());

}

From source file:org.wso2.carbon.identity.certificateauthority.dao.CrlDataHolderDao.java

License:Open Source License

/**
 * add crl data into database table CA_CRL_STORE
 *
 * @param crl               x509 crl//  w  w w.j  a va  2s. co m
 * @param tenantID          issuer of the crl
 * @param thisUpdate        time of this update
 * @param nextUpdate        time of next crl will be released
 * @param crlNumber         contiuolusly increasing number for a tenant
 * @param deltaCrlIndicator
 * @throws CRLException
 * @throws CaException
 */
public void addCRL(X509CRL crl, int tenantID, Date thisUpdate, Date nextUpdate, int crlNumber,
        int deltaCrlIndicator) throws CRLException, CaException {
    Connection connection = null;
    String sql = null;
    PreparedStatement prepStmt = null;
    try {
        log.debug("adding CRL to database");
        connection = JDBCPersistenceManager.getInstance().getDBConnection();
        Date date = new Date();
        sql = "INSERT INTO CA_CRL_STORE (BASE64CRL, THIS_UPDATE, NEXT_UPDATE, CRL_NUMBER, DELTA_CRL_INDICATOR, TENANT_ID) VALUES (?,?,?,?,?,?) ";
        prepStmt = connection.prepareStatement(sql);
        prepStmt.setString(1, new String(Base64.encode((crl).getEncoded())));
        prepStmt.setTimestamp(2, new Timestamp(thisUpdate.getTime()));
        prepStmt.setTimestamp(3, new Timestamp(nextUpdate.getTime()));
        prepStmt.setInt(4, crlNumber);
        prepStmt.setInt(5, deltaCrlIndicator);
        prepStmt.setInt(6, tenantID);
        prepStmt.execute();
        connection.commit();
    } catch (IdentityException e) {
        String errorMsg = "Error when getting an Identity Persistence Store instance.";
        log.error(errorMsg, e);
        throw new CaException(errorMsg, e);
    } catch (SQLException e) {
        log.error("Error when executing the SQL : " + sql);
        log.error(e.getMessage(), e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, null, prepStmt);
    }
}