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.jscep.request.PKCSReq.java

License:Open Source License

/**
 * {@inheritDoc}/*from   ww  w .ja  v a 2  s.  co  m*/
 */
public String getMessage() throws IOException {
    byte[] bytes = Base64.encode(msgData.getEncoded());

    return new String(bytes);
}

From source file:org.kercoin.tests.scenarii.DiffieHellmanTest.java

License:Open Source License

@Test
public void aliceSaysHelloToBob() throws Exception {
    // given/*from  w w  w  .  java 2s  .c  o  m*/
    alice = new PeerImpl(dhParameterSpec);
    bob = new PeerImpl(dhParameterSpec);

    // when
    final byte[] aliceShared = alice.agree().with(bob.getPublic()).getSharedKey();
    final byte[] bobShared = bob.agree().with(alice.getPublic()).getSharedKey();

    // then
    assertThat(aliceShared).isEqualTo(bobShared);
    log.info("Shared {}", new String(Base64.encode(aliceShared)));
}

From source file:org.krakenapps.ca.msgbus.CaPlugin.java

License:Apache License

@MsgbusMethod
public void getPfxFile(Request req, Response resp) {
    String authorityName = req.getString("authority");
    String serial = req.getString("serial");

    // check authority
    CertificateAuthority authority = ca.getAuthority(authorityName);
    if (authority == null)
        throw new MsgbusException("kraken-ca", "authority-not-found");

    CertificateMetadata cm = authority.findCertificate("serial", serial);
    if (cm == null)
        throw new MsgbusException("kraken-ca", "certificate-not-found");

    byte[] encoded = Base64.encode(cm.getBinary());

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < encoded.length; i++)
        sb.append((char) encoded[i]);

    resp.put("pfx", sb.toString());
}

From source file:org.kse.crypto.signing.MidletSigner.java

License:Open Source License

/**
 * Sign a JAD file outputting the modified JAD to a different file.
 *
 * @param jadFile/* w  w  w  .  jav  a  2  s  . com*/
 *            JAD file
 * @param outputJadFile
 *            Output JAD file
 * @param jarFile
 *            JAR file
 * @param privateKey
 *            Private RSA key to sign with
 * @param certificateChain
 *            Certificate chain for private key
 * @param certificateNumber
 *            Certificate number
 * @throws IOException
 *             If an I/O problem occurs while signing the MIDlet
 * @throws CryptoException
 *             If a crypto problem occurs while signing the MIDlet
 */
public static void sign(File jadFile, File outputJadFile, File jarFile, RSAPrivateKey privateKey,
        X509Certificate[] certificateChain, int certificateNumber) throws IOException, CryptoException {
    Properties jadProperties = readJadFile(jadFile);

    Properties newJadProperties = new Properties();

    // Copy over existing attrs (excepting digest and any certificates at
    // provided number)
    for (Enumeration<?> enumPropNames = jadProperties.propertyNames(); enumPropNames.hasMoreElements();) {
        String propName = (String) enumPropNames.nextElement();

        // Ignore digest attr
        if (propName.equals(MIDLET_JAR_RSA_SHA1_ATTR)) {
            continue;
        }

        // Ignore certificates at provided number
        if (propName.startsWith(MessageFormat.format(SUB_MIDLET_CERTIFICATE_ATTR, certificateNumber))) {
            continue;
        }

        newJadProperties.put(propName, jadProperties.getProperty(propName));
    }

    // Get certificate attrs
    for (int i = 0; i < certificateChain.length; i++) {
        X509Certificate certificate = certificateChain[i];
        String base64Cert = null;
        try {
            base64Cert = new String(Base64.encode(certificate.getEncoded()));
        } catch (CertificateEncodingException ex) {
            throw new CryptoException(res.getString("Base64CertificateFailed.exception.message"), ex);
        }

        String midletCertificateAttr = MessageFormat.format(MIDLET_CERTIFICATE_ATTR, certificateNumber,
                (i + 1));
        newJadProperties.put(midletCertificateAttr, base64Cert);
    }

    // Get signed Base 64 SHA-1 digest of JAR file as attr
    byte[] signedJarDigest = signJarDigest(jarFile, privateKey);
    String base64SignedJarDigest = new String(Base64.encode(signedJarDigest));
    newJadProperties.put(MIDLET_JAR_RSA_SHA1_ATTR, base64SignedJarDigest);

    // Sort properties alphabetically
    TreeMap<String, String> sortedJadProperties = new TreeMap<String, String>();

    for (Enumeration<?> names = newJadProperties.propertyNames(); names.hasMoreElements();) {
        String name = (String) names.nextElement();
        String value = newJadProperties.getProperty(name);

        sortedJadProperties.put(name, value);
    }

    // Write out new JAD properties to JAD file
    FileWriter fw = null;

    try {
        fw = new FileWriter(outputJadFile);

        for (Iterator<Entry<String, String>> itrSorted = sortedJadProperties.entrySet().iterator(); itrSorted
                .hasNext();) {
            Entry<String, String> property = itrSorted.next();

            fw.write(MessageFormat.format(JAD_ATTR_TEMPLATE, property.getKey(), property.getValue()));
            fw.write(CRLF);
        }
    } finally {
        IOUtils.closeQuietly(fw);
    }
}

From source file:org.mailster.core.pop3.commands.auth.AuthCramCommand.java

License:Open Source License

public Pop3CommandState challengeClient(AbstractPop3Handler handler, AbstractPop3Connection conn, String cmd)
        throws UnsupportedEncodingException {
    conn.println("+ " + new String(
            Base64.encode(
                    conn.getState().getGeneratedAPOPBanner().getBytes(MailsterConstants.DEFAULT_CHARSET_NAME)),
            MailsterConstants.DEFAULT_CHARSET_NAME));

    return new Pop3CommandState(this, CHECK_RESPONSE_TO_CHALLENGE_STATE);
}

From source file:org.mailster.core.pop3.commands.auth.AuthDigestMD5Command.java

License:Open Source License

public Pop3CommandState challengeClient(AbstractPop3Handler handler, AbstractPop3Connection conn, String cmd)
        throws Exception {
    byte[] nonce = new byte[20];
    rnd.nextBytes(nonce);/*from w  w w .ja  v  a 2s.  co m*/
    String realm = InetAddress.getLocalHost().getCanonicalHostName();
    String serverNonce = new String(Base64.encode(nonce), "utf8");

    StringBuilder sb = new StringBuilder();
    sb.append("realm=\"").append(realm);
    sb.append("\",nonce=\"");
    sb.append(serverNonce);
    sb.append("\",qop=\"auth, auth-int");

    boolean foundAvailableCipher = false;
    for (CIPHER cipher : CIPHER.values()) {
        if (CIPHER.isSupported(cipher)) {
            if (foundAvailableCipher)
                sb.append(", ");
            else {
                sb.append(", auth-conf\",cipher=\"");
                foundAvailableCipher = true;
            }
            sb.append(cipher.toString());
        }
    }
    sb.append("\",");
    sb.append("algorithm=md5-sess,charset=utf-8");

    HashMap<String, Object> sessionMap = new HashMap<String, Object>();
    sessionMap.put("realm", realm);
    sessionMap.put("nonce", serverNonce);
    sessionMap.put("qop", SUPPORTED_QOPS);

    IoSession session = ((MinaPop3Connection) conn).getSession();
    session.setAttribute(DIRECTIVES_MAP, sessionMap);

    byte[] challengeBytes = sb.toString().getBytes("utf8");
    if (challengeBytes.length > 2048)
        throw new AuthException("Server response size exceeds 2048 bytes");

    String challenge = new String(Base64.encode(challengeBytes), "utf8");

    conn.println("+ " + challenge.replaceAll("\n", "").toString());

    return new Pop3CommandState(this, CHECK_RESPONSE_TO_CHALLENGE_STATE);
}

From source file:org.mailster.core.pop3.commands.auth.AuthDigestMD5Command.java

License:Open Source License

@SuppressWarnings("unchecked")
public Pop3CommandState checkClientResponse(AbstractPop3Handler handler, AbstractPop3Connection conn,
        String cmd) throws Exception {
    String decoded = new String(Base64.decode(cmd.getBytes("utf8")), "utf8");
    if (decoded.getBytes("utf8").length > 4096)
        throw new AuthException("Digest-response size exceeds 4096 bytes");

    HashMap<String, String> map = StringUtilities.parseDirectives(decoded.getBytes("utf8"));

    if (!getDirectiveValue(map, "nc", true).equals("00000001"))
        throw new AuthException("Nonce-count value is wrong");

    IoSession session = ((MinaPop3Connection) conn).getSession();

    HashMap<String, String> sessionMap = (HashMap<String, String>) session.getAttribute(DIRECTIVES_MAP);

    if (!getDirectiveValue(sessionMap, "realm", true).equals(getDirectiveValue(map, "realm", true))
            || !getDirectiveValue(sessionMap, "nonce", true).equals(getDirectiveValue(map, "nonce", true)))
        throw new AuthException("Negociation failed");

    HashMap<String, String[]> sMap = (HashMap<String, String[]>) session.getAttribute(DIRECTIVES_MAP);
    String qop = getDirectiveValue(map, "qop", true);
    boolean matched = false;
    for (String s : sMap.get("qop")) {
        if (s.equals(qop)) {
            matched = true;//from w  ww. ja va2  s .  c o m
            break;
        }
    }

    if (!matched)
        throw new AuthException("Unsupported qop");

    if (qop.equals("auth-conf"))
        session.setAttribute(NEGOCIATED_CIPHER, CIPHER.getByName(getDirectiveValue(map, "cipher", true)));

    Pop3State state = conn.getState();
    state.setUser(state.getUser(getDirectiveValue(map, "username", true)));
    String charset = getDirectiveValue(map, "charset", false);
    charset = charset == null || !"utf8".equals(charset) ? "8859_1" : "utf8";
    session.setAttribute(ENCODING, charset);

    String maxbuf = getDirectiveValue(map, "maxbuf", false);
    int clientMaxBufSize = maxbuf == null ? DEFAULT_MAXBUF : Integer.parseInt(maxbuf);
    if (clientMaxBufSize < 16 || clientMaxBufSize > DEFAULT_MAXBUF)
        throw new AuthException("Wrong maxbuf value");
    else
        session.setAttribute(CLIENT_MAXBUF, clientMaxBufSize);

    String response = getDirectiveValue(map, "response", true);
    computeA1(session, map, conn.getState().getUser().getPassword(), charset);

    if (!response.equals(computeResponseValue(session, map, false)))
        throw new AuthException("Response check failed");
    else {
        String responseAuth = "rspauth=" + computeResponseValue(session, map, true);
        conn.println("+ " + new String(Base64.encode(responseAuth.getBytes(charset)), charset));

        if (qop.equals("auth-int"))
            return new Pop3CommandState(this, GET_CLIENT_ACK_WITH_INTEGRITY_QOP_STATE);
        else if (qop.equals("auth-conf"))
            return new Pop3CommandState(this, GET_CLIENT_ACK_WITH_PRIVACY_QOP_STATE);
    }

    return new Pop3CommandState(this, GET_CLIENT_ACK_STATE);
}

From source file:org.mkdev.ut.EncryptorTest.java

License:GNU General Public License

@Test
public void testEncryptString() throws CryptoException {
    System.out.println(new String(Base64.encode(encryptor.encryptString("alamakota"))));
}

From source file:org.mkdev.ut.PropertiesEncryptedUtil.java

License:GNU General Public License

private void encryptPropertyValue(Field field) throws Exception {
    String value = (String) field.get(this);

    String encryptedValue = new String(Base64.encode(encryptor.encryptString(value)));

    LOGGER.debug("key=[{}], value=[{}]", field.getName(), encryptedValue);

    field.set(this, encryptedValue);
}

From source file:org.objectweb.proactive.core.security.CertTools.java

License:Open Source License

/**
 * Returns a certificate in PEM-format./*  w  w w .  ja  v a 2s.  c o m*/
 *
 * @param certs the certificate to convert to PEM
 * @return byte array containing PEM certificate
 * @exception IOException if the stream cannot be read.
 * @exception CertificateException if the stream does not contain a correct certificate.
 */
public static byte[] getPEMFromCerts(Collection<X509Certificate> certs) throws CertificateException {
    String beginKey = "-----BEGIN CERTIFICATE-----";
    String endKey = "-----END CERTIFICATE-----";
    ByteArrayOutputStream ostr = new ByteArrayOutputStream();
    PrintStream opstr = new PrintStream(ostr);
    Iterator<X509Certificate> iter = certs.iterator();
    while (iter.hasNext()) {
        X509Certificate cert = iter.next();
        byte[] certbuf = Base64.encode(cert.getEncoded());
        opstr.println("Subject: " + cert.getSubjectDN());
        opstr.println("Issuer: " + cert.getIssuerDN());
        opstr.println(beginKey);
        opstr.println(new String(certbuf));
        opstr.println(endKey);
    }
    opstr.close();
    byte[] ret = ostr.toByteArray();
    return ret;
}