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:test.junit.Pop3DigestMD5Test.java

License:Open Source License

private void sendAuthDigestMD5(String selectedQop, CIPHER cipher) throws Exception {
    println("AUTH DIGEST-MD5");
    byte[] decoded = Base64.decode(readLine().substring(2));
    HashMap<String, String> map = StringUtilities.parseDirectives(decoded);
    StringBuilder sb = new StringBuilder();
    sb.append("username=\"").append(USER).append("\",");
    sb.append("nonce=\"").append(map.get("nonce")).append("\",");
    sb.append("cnonce=\"").append("hjds54s4dJZI").append("\",");
    sb.append("realm=\"").append(map.get("realm")).append("\",");
    sb.append("charset=").append(encoding).append(",");
    sb.append("qop=\"").append(selectedQop);
    sb.append("\",");
    sb.append("maxbuf=").append(CLIENT_MAXBUF);

    if (selectedQop.equals("auth-conf"))
        sb.append(",cipher=").append(cipher);

    sb.append(",nc=00000001,");
    sb.append("digest-uri=\"pop3/").append(map.get("realm")).append("\"");
    HashMap<String, String> clientMap = StringUtilities.parseDirectives(sb.toString().getBytes(encoding));
    sb.append(",response=").append(computeResponseValue(clientMap, PWD, encoding, false));

    println(new String(Base64.encode(sb.toString().getBytes(encoding)), encoding));
    String response = new String(Base64.decode(readLine().substring(2).getBytes(encoding)), encoding);

    assertTrue(response, response.startsWith("rspauth"));
    String computed = computeResponseValue(clientMap, PWD, encoding, true);
    assertTrue(computed, computed.equals(response.substring(8)));
    println("");//from  w ww .jav  a2  s .  c  o m
    response = readLine();
    assertTrue(response, response.startsWith("+OK "));
    integrityModeEnabled = selectedQop.equals("auth-int");
    privacyModeEnabled = selectedQop.equals("auth-conf");

    if (privacyModeEnabled)
        computePrivacyKeys(cipher, encoding, true);
}

From source file:TorJava.Common.Encryption.java

License:Open Source License

/**
 * converts a JCERSAPublicKey into PEM/PKCS1-encoding
 * /*  www.  j a  v a  2  s.co  m*/
 * @param rsaPublicKey
 * @see RSAPublicKeyStructure
 * @return PEM-encoded RSA PUBLIC KEY
 */
public static String getPEMStringFromRSAPublicKey(RSAPublicKeyStructure rsaPublicKey) {

    // mrk: this was awful to program. Remeber: There are two entirely
    // different
    // standard formats for rsa public keys. Bouncy castle does only support
    // the
    // one we can't use for TOR directories.

    StringBuffer tmpDirSigningKey = new StringBuffer();

    try {

        tmpDirSigningKey.append("-----BEGIN RSA PUBLIC KEY-----\n");

        byte[] base64Encoding = Base64.encode(getPKCS1EncodingFromRSAPublicKey(rsaPublicKey));
        for (int i = 0; i < base64Encoding.length; i++) {
            tmpDirSigningKey.append((char) base64Encoding[i]);
            if (((i + 1) % 64) == 0)
                tmpDirSigningKey.append("\n");
        }
        tmpDirSigningKey.append("\n");

        tmpDirSigningKey.append("-----END RSA PUBLIC KEY-----\n");
    } catch (Exception e) {
        return null;
    }

    return tmpDirSigningKey.toString();
}

From source file:uk.co.develop4.security.utils.decoders.Base64Decoder.java

License:Apache License

public String encrypt(String cleartext, String label) {
    if (cleartext == null) {
        return null;
    }/* w  ww  .j  av a 2  s  .co  m*/
    return NAMESPACE + new String(Base64.encode(cleartext.getBytes()));
}

From source file:umu.eadmin.servicios.umu2stork.EduGAIN2StorkProxy.java

License:Open Source License

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)/*from   w  ww.  j a  v  a  2s . c om*/
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // TODO Auto-generated method stub
    logger.info("---- edupeps::EduGAIN2StorkProxy::doPost() ----");

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    i18n = new Properties();
    i18n.load(ReturnPage.class.getClassLoader().getResourceAsStream("en.properties")); //default

    UtilesRsa encoder = new UtilesRsa();

    out.println(HTML_START);
    out.println(HTML_HEAD);
    // AUTO-LOAD FORM
    //out.println("<body style=\"background-image:url(webapp/img/background.png); background-size:scale; background-repeat: no-repeat;background-position: center top\" onload=\"document.createElement('form').submit.call(document.getElementById('myForm'))\">");
    // NO AUTO-LOAD
    out.println(
            "<body style=\"background-image:url(webapp/img/background.png); background-size:scale; background-repeat: no-repeat;background-position: center top\">");

    // Enumeration <String> params = request.getParameterNames();

    Map<String, String> headerparammap = new HashMap<String, String>();
    Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String key = (String) headerNames.nextElement();
        String value = request.getHeader(key);
        headerparammap.put(key, value);
    }
    for (String aux : headerparammap.values()) {
        logger.info("\tparam: " + aux);
    }

    String jsessionid = "";
    try {
        String cookie = headerparammap.get("cookie");
        if (cookie != null) {
            logger.info("Cookie: " + cookie);
            String[] cookiesplt = cookie.split("=");
            if (cookiesplt.length < 1)
                throw new ServletException("Unable to recover jsessionid, regex problem over: " + cookie);
            jsessionid = cookiesplt[1];
        } else {
            logger.warning("No cookie found!!");
        }
    } catch (ClassCastException cce) {
        logger.severe("Unable to recover jsessionid\n" + cce);
        throw new ServletException(
                "eduGAIN2StorkProxy::DoPost() - Unable to recover jsessionid (InvalidCast)\n" + cce);
    } catch (NullPointerException npe) {
        logger.severe("Unable to recover jsessionid\n" + npe);
        throw new ServletException(
                "eduGAIN2StorkProxy::DoPost() - Unable to recover jsessionid (null)\n" + npe);
    } catch (java.lang.IndexOutOfBoundsException iobe) {
        logger.severe("Unable to recover jsessionid - Malformed cookie\n" + iobe);
        throw new ServletException(
                "eduGAIN2StorkProxy::DoPost() - Unable to recover jsessionid (IndexOutOfBoundsException)\n"
                        + iobe);
    }

    // Load Multi-language i18n
    String langparam = request.getParameter(LANGHEADERSTR);
    if (langparam != null)
        if (langparam.equals("es")) {
            i18n = new Properties();
            i18n.load(ReturnPage.class.getClassLoader().getResourceAsStream("es.properties"));
        } else
            langparam = "en";

    /*** SAMLInt ***/
    // Recover SAML_int request and parse
    // https://wiki.shibboleth.net/confluence/display/OpenSAML/OSTwoUsrManJavaCreateFromXML
    String samlreq = request.getParameter(SAMLIntREQSTR);
    if (samlreq == null) {
        logger.severe("FATAL ERROR: Missing SAML Int Request!");
        this.log("FATAL ERROR: Missing SAML Int Request!");
        closeWithError(out, i18n, "error.proxy.saml.missing");
        return;
    }

    logger.info("We have a SAMLRequest");
    logger.info("samlreq=" + samlreq);
    byte[] samlreqbase64decoded = Base64.decode(samlreq.getBytes("UTF-8"));
    logger.info("samlreqbase64decoded=" + new String(samlreqbase64decoded));

    byte[] samlreqinflated = null;
    try {
        //try DEFLATE (rfc 1951) -- according to SAML spec
        samlreqinflated = inflate(samlreqbase64decoded, true);
        logger.info("samlreqinflated=" + new String(samlreqinflated));
    } catch (Exception e) {
        logger.severe("FATAL ERROR: SAMLRequest could not be inflated");
        this.log("FATAL ERROR: SAMLRequest could not be inflated");
        closeWithError(out, i18n, "error.proxy.saml.inflate");
    }

    //InputStream samlreqstream = new ByteArrayInputStream(samlreqbase64decoded);
    InputStream samlreqstream = new ByteArrayInputStream(samlreqinflated);

    String returnPageUrlSP = null;
    String SPIssuer = null;
    try {
        Document samlreqdoc = ppMgr.parse(samlreqstream);
        Element samlelement = samlreqdoc.getDocumentElement();
        UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
        Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(samlelement);
        AuthnRequest authnRequestSAML = null;
        try {
            authnRequestSAML = (AuthnRequest) unmarshaller.unmarshall(samlelement);
            SPIssuer = authnRequestSAML.getIssuer().getValue();
            logger.info("issuer: " + SPIssuer);
            returnPageUrlSP = authnRequestSAML.getAssertionConsumerServiceURL();
            logger.info("consumerService-returnpage: " + returnPageUrlSP);
            //Signature sig = authnRequestSAML.getSignature();
        } catch (UnmarshallingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } catch (XMLParserException xmlparsee) {
        logger.severe("Unable to xml parse SAMLint Request)" + xmlparsee);
        throw new ServletException("ERROR: Unable to xml parse SAMLint Request");
    }
    out.println("</BR></BR>");

    // Country code attribute recovery
    String countryCodeParam = request.getParameter("CountryCode");
    if (countryCodeParam == null) {
        logger.severe("FATAL ERROR: Missing Country Code Parameter, abort!");
        this.log("FATAL ERROR: Missing Country Code Parameter, abort!");
        closeWithError(out, i18n, "error.proxy.contrycode");
        return;
    }
    logger.info("CountryCode: " + countryCodeParam);

    logger.info("Creando Personal Attribute List para consulta");
    PersonalAttributeList pal = new PersonalAttributeList();
    PersonalAttribute pa = null;

    // Serviceparam indicates configuration var to select the attributes to request. To be removed when SAMLint request is fine
    String serviceparam = properties.getProperty(PROPERTIES_PROXY_URL_PARAM);
    boolean appfound = false;
    for (String app : optattributesxapp.keySet()) {
        logger.info("Checking: "
                + properties.getProperty(PROPERTIES_APP_PARAM_PREFIX + "." + app + PROPERTIES_APP_URL_POSTFIX)
                + " vs " + serviceparam + "</BR>");
        if (properties.getProperty(PROPERTIES_APP_PARAM_PREFIX + "." + app + PROPERTIES_APP_URL_POSTFIX)
                .equals(serviceparam)) {
            if (optattributesxapp.containsKey(app)) {
                String[] mandattrs = mandattributesxapp.get(app);
                for (String attr : mandattrs) {
                    logger.info("Mandatory " + app + " : " + attr);
                    pa = new PersonalAttribute();
                    pa.setName(attr);
                    pa.setIsRequired(true);
                    pal.add(pa);
                }

                String[] attrs = optattributesxapp.get(app);
                for (String attr : attrs) {
                    logger.info("Optional " + app + " : " + attr);
                    pa = new PersonalAttribute();
                    pa.setName(attr);
                    pa.setIsRequired(false);
                    pal.add(pa);
                }
                appfound = true;
            }
        }
    }
    if (!appfound) {
        logger.info("Servicio Desconocido " + serviceparam);
        closeWithError(out, i18n, "error.proxy.appunk");
        return;

    }

    int QAA = 1;

    final String destinationURL = EduGAIN2StorkProxy.PEPSPageUrl;
    final String assertConsumerUrl = EduGAIN2StorkProxy.returnPageUrl;

    final String spName = EduGAIN2StorkProxy.spname;
    final String spSector = EduGAIN2StorkProxy.spsector;
    final String spInstitution = EduGAIN2StorkProxy.spinstitution;
    final String spApplication = EduGAIN2StorkProxy.spapp;
    final String spCountry = EduGAIN2StorkProxy.spcountry;
    final String spId = EduGAIN2StorkProxy.spid;

    final STORKAuthnRequest authRequest = new STORKAuthnRequest();

    logger.info("Generating STORK Auth Request");

    authRequest.setDestination(destinationURL);
    authRequest.setProviderName(spName);
    authRequest.setQaa(QAA);
    authRequest.setPersonalAttributeList(pal);
    authRequest.setAssertionConsumerServiceURL(assertConsumerUrl);

    // new parameters
    authRequest.setSpSector(spSector);
    authRequest.setSpInstitution(spInstitution);
    authRequest.setSpApplication(spApplication);
    authRequest.setSpCountry(spCountry);
    authRequest.setSPID(spId);
    authRequest.setCitizenCountryCode(countryCodeParam);
    authRequest.setPersonalAttributeList(pal);

    logger.info("Recuperando STORK Engine");

    STORKSAMLEngine engine = STORKSAMLEngine.getInstance("SP"); // SP -
    // Magic
    // Number?

    String authReqSTORKString = "";
    final STORKAuthnRequest saml;
    try {
        logger.info("Generate STORK SAML Auth Request from auth Request");
        saml = engine.generateSTORKAuthnRequest(authRequest);
        byte[] authReqSTORKbytes = Base64.encode(saml.getTokenSaml());
        authReqSTORKString = new String(authReqSTORKbytes);
        logger.info("STORKAuthnRequest Size: " + authReqSTORKbytes);
        logger.info("STORKAuthnRequest String: " + authReqSTORKString);
        logger.info("STORKAuthnRequest Id: " + saml.getSamlId());

        out.println("<form id='myForm' name='myForm' action='" + destinationURL + "' method='post'>");
        out.println("<input type='hidden' name='country' value='" + countryCodeParam + "'>");
        out.println("<input type='hidden' name='SAMLRequest' value='" + authReqSTORKString + "'>");
        out.println(
                "<center><button type='submit' value='Send' method='post'><img src='webapp/img/send.png' width=25 border=3></button></center>");
        out.println("</form>");

    } catch (STORKSAMLEngineException e) {
        out.println(i18n.getProperty("error.proxy.saml") + " " + e);
        logger.severe("Engine error generating the Stork Authn Request");
        e.printStackTrace();
    }

    // SAVE SESSION
    // saveSession(String jsessionid, String uuid, String appname, String url, String service, String lang)
    try {
        this.proxyH2db.saveSession(jsessionid, "", "", returnPageUrlSP, SPIssuer, langparam);
    } catch (Exception e) {
        throw new ServletException("DB Problem: " + e);
    }

    Date date = new Date();

    out.println("<h2>" + i18n.getProperty("info.proxy.wait") + "</h2><br/><h3>Date=" + date + "</h3><br>");

    out.println("</body>");
    out.println(HTML_END);
    out.close();

}

From source file:umu.eadmin.servicios.umu2stork.UtilesRsa.java

License:Open Source License

public String encode(String data) throws javax.servlet.ServletException {
    String output = "";
    if (pk == null)
        throw new ServletException("Private ciphering key does not exist!");
    try {/*from  w w w  .j  av a  2s.  co  m*/
        logger.info("RSA encoder load");
        Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        logger.info("RSA encoder init");
        rsaCipher.init(Cipher.ENCRYPT_MODE, pk);
        int inputSize = data.length();
        int inputBlockSize = rsaCipher.getOutputSize(1);
        int numBlocks = inputSize / inputBlockSize;
        logger.info("#Blocks: " + numBlocks);
        int resto = inputSize % inputBlockSize;

        byte[][] rawOutput = null;
        if (resto != 0)
            rawOutput = new byte[numBlocks + 1][];
        else
            rawOutput = new byte[numBlocks][];

        int blockCount = 0;
        while (blockCount < numBlocks) {
            int index = blockCount * inputBlockSize;
            rawOutput[blockCount] = rsaCipher.doFinal(data.getBytes(), index, inputBlockSize);
            logger.info("Block encoded: " + new String(rawOutput[blockCount]));
            blockCount++;
        }

        if (resto != 0) {
            numBlocks++;
            int index = blockCount * inputBlockSize;
            rawOutput[blockCount] = rsaCipher.doFinal(data.getBytes(), index, resto);
        }

        int totalSize = 0;
        for (int i = 0; i < numBlocks; i++)
            totalSize += rawOutput[i].length;

        byte[] fullOutput = new byte[totalSize];

        int count = 0;
        for (int i = 0; i < numBlocks; i++) {
            int blockSize = rawOutput[i].length;
            for (int j = 0; j < blockSize; j++) {
                fullOutput[count] = rawOutput[i][j];
                count++;
            }
        }

        byte[] encoded64Data = Base64.encode(fullOutput);

        output = new String(encoded64Data);
        logger.info("RSA Encoding ends");

    } catch (Exception e) {
        logger.warning("Encoding aborted due Exception: " + e);
        output = "";
    }
    return output;
}

From source file:wsattacker.library.xmlencryptionattack.attackengine.pkcs1.BleichenbacherAttackerTest.java

License:Open Source License

@Test
@Ignore/*from  w  w  w.j a  v a  2 s.  c  o  m*/
public void testAttackPerformance() throws Exception {

    System.out.println("Bleichenbacher Attack test with a constant message");

    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(1024);
    KeyPair keyPair = keyGen.genKeyPair();
    RSAPublicKey pubKey = (RSAPublicKey) keyPair.getPublic();

    TestPKCS1PlaintextOracle oracle = new TestPKCS1PlaintextOracle(pubKey);

    int blockSize = pubKey.getModulus().bitLength() / 8;
    System.out.println(blockSize);
    byte[] dummyKey = new byte[blockSize];
    Random r = new Random();
    r.nextBytes(dummyKey);
    dummyKey[0] = 0;
    dummyKey[1] = 2;

    BleichenbacherPlaintextAttacker instance = new BleichenbacherPlaintextAttacker(dummyKey, oracle);
    byte[] result = instance.executeAttack();

    LOG.info("The decrypted message was found after " + oracle.getNumberOfQueries() + " queries:\n "
            + Utility.bytesToHex(result));

    Cipher cipher = Cipher.getInstance("RSA/None/NoPadding", new BouncyCastleProvider());
    cipher.init(Cipher.ENCRYPT_MODE, oracle.getPublicKey());
    byte[] encKey = cipher.doFinal(dummyKey);

    LOG.info("Encrypted Key in Base64: " + new String(Base64.encode(encKey)));

}

From source file:xmlgenerator.SignDispatch.java

public boolean signTimeStamp() throws SAXException, ParserConfigurationException, IOException {
    byte[] digest = getSignature().getBytes();

    try {//from  ww  w.  ja v a  2 s .c o  m
        String str = getTimestamp(new String(Base64.encode(digest)));
        byte[] out = Base64.decode(str.getBytes());
        TimeStampResponse tsResponse = new TimeStampResponse(out);
        TimeStampToken tsToken = tsResponse.getTimeStampToken();
        signWithTimeStamp(new String(Base64.encode(tsToken.getEncoded())));
        return true;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}