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:piecework.security.concrete.ExampleBouncyCastleEncryptionService.java

License:Educational Community License

@Override
public String generateKey(int keySize)
        throws NoSuchAlgorithmException, InvalidKeySpecException, UnsupportedEncodingException {
    LOG.info("Generating a new encryption key of size " + keySize);
    KeyGenerator keyGen = KeyGenerator.getInstance("AES");
    keyGen.init(keySize);/*from  w  w w .  j a va  2s .  co m*/
    SecretKey secretKey = keyGen.generateKey();
    return new String(Base64.encode(secretKey.getEncoded()), "UTF-8");
}

From source file:pt.iflow.api.utils.JarSigner15.java

License:Apache License

private static String updateDigest(MessageDigest digest, InputStream inputStream) throws IOException {
    byte[] buffer = new byte[2048];
    int read = 0;
    while ((read = inputStream.read(buffer)) > 0)
        digest.update(buffer, 0, read);// w  ww . jav a 2 s .c  om
    inputStream.close();

    return new String(Base64.encode(digest.digest()));

}

From source file:rotmg.actions.outgoing.HelloAction.java

License:Open Source License

/**
 *   private function encryptWithPublicKey(param1:String) : String {
 var rsaPublicKey:RSAKey = PEM.readRSAPublicKey(UserConfig.rotmgPEM);
 var bytesToEncrypt:ByteArray = new ByteArray();
 bytesToEncrypt.writeUTFBytes(param1);//from   w ww  .  j a v a  2  s.  c  o  m
 var encryptedBytes:ByteArray = new ByteArray();
 rsaPublicKey.encrypt(bytesToEncrypt,encryptedBytes,bytesToEncrypt.length);
 return Base64.encodeByteArray(encryptedBytes);
 */
private String encryptWithPublicKey(String thingToEncrypt) throws IOException {
    try (Reader reader = new StringReader(RotmgParameters.ROTMG_PUBLIC_KEY);
            PEMReader pemReader = new PEMReader(reader)) {
        Security.addProvider(new BouncyCastleProvider());
        PublicKey publicKey = (PublicKey) pemReader.readObject();
        Cipher rsa = Cipher.getInstance("RSA");
        rsa.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] encryptedBytes = rsa.doFinal(thingToEncrypt.getBytes());
        return new String(Base64.encode(encryptedBytes));
    } catch (IllegalBlockSizeException | BadPaddingException | NoSuchAlgorithmException | NoSuchPaddingException
            | InvalidKeyException e) {
        throw new IOException("Could not encrypt.", e);
    }
}

From source file:ru.jts.loginserver.network.game_client.crypt.PasswordHash.java

License:Apache License

public static String hash(String input, String algorithm) {
    MessageDigest digest;// www . ja v a2s.  co m
    String hash = input;
    switch (algorithm) {
    case "whirlpool":
        digest = new JDKMessageDigest.Whirlpool();
        byte[] outputBytes = digest.digest(input.getBytes());
        hash = new String(Base64.encode(outputBytes));
        break;
    default:
        Log.w(LOG_TAG, "Algorithm {} not found! string {} is not been hashed", algorithm, input);
    }
    return hash;
}

From source file:ru.pflb.samlsampler.SamlSampler.java

@Override
public SampleResult runTest(JavaSamplerContext jsc) {
    String pathToPrivateKey = jsc.getParameter("Path to EMP private key");
    String strAssertionConsumerServiceURL = jsc.getParameter("AssertionConsumerServiceURL");
    String strDestination = jsc.getParameter("Destination");
    String strAssertion = jsc.getParameter("Assertion");
    String strURL_SSO = jsc.getParameter("URL_SSO");
    String strSigAlg = jsc.getParameter("SigAlg");

    String varSAMLRequest = jsc.getParameter("SaveToVarSAMLRequest");
    String varRelayState = jsc.getParameter("SaveToVarRelayState");
    String varSignature = jsc.getParameter("SaveToVarSignature");

    SampleResult result = new SampleResult();
    result.sampleStart(); // start stopwatch

    try {/*from   w w w . j a  v  a2s .c o  m*/

        result.sampleEnd();

        String xml = createSamlXml(strAssertionConsumerServiceURL, strDestination, strAssertion);

        //PrivateKey privateKey = getEPMPrivateKey(pathToPrivateKey);
        PrivateKey privateKey = getEPMPrivateKey(pathToPrivateKey);

        String encoded = deflateAndBase64encode(xml);
        encoded.replaceAll("\n|\r\n", "");
        String sSAMLRequestNOTencoded = encoded;
        encoded = URLEncoder.encode(encoded, "UTF-8");

        //strURL_SSO += encoded;

        //String URL = URLEncoder.encode(encoded, "UTF-8");
        //byte[] signature = getSignature(URL, privateKey, "SHA1withRSA");

        //String sSAMLRequest = new String(outbase64);
        String sSAMLRequest = encoded;
        String sRelayState = UUID.randomUUID().toString();
        String sSigAlg = "http://www.w3.org/2000/09/xmldsig#rsa-sha1";
        //

        strURL_SSO = strURL_SSO + sSAMLRequest + "&RelayState=_" + URLEncoder.encode(sRelayState, "UTF-8")
                + "&SigAlg=" + URLEncoder.encode(strSigAlg, "UTF-8");
        //strURL_SSO = URLEncoder.encode(strURL_SSO+sSAMLRequest+"&RelayState=_"+sRelayState+"&SigAlg="+strSigAlg,"UTF-8");
        byte[] signature = getSignature(strURL_SSO, privateKey, "SHA1withRSA");
        String sSignature = new String(Base64.encode(signature));

        JMeterVariables vars = JMeterContextService.getContext().getVariables();
        vars.putObject(varSAMLRequest, sSAMLRequestNOTencoded);
        vars.putObject(varRelayState, "_" + sRelayState);
        vars.putObject("varSigAlg", strSigAlg);
        vars.putObject(varSignature, sSignature);
        JMeterContextService.getContext().setVariables(vars);
        result.setResponseData(
                "==================================================================================================="
                        + "\r\n" + "URL: " + strURL_SSO + "\r\n"
                        + "==================================================================================================="
                        + "\r\n" + "XML: " + xml + "\r\n"
                        + "==================================================================================================="
                        + "\r\n" + "SAMLRequest: " + sSAMLRequest + "\r\n"
                        + "==================================================================================================="
                        + "\r\n" + "RelayState: " + "_" + sRelayState + "\r\n"
                        + "==================================================================================================="
                        + "\r\n" + "SigAlg: " + sSigAlg + "\r\n"
                        + "==================================================================================================="
                        + "\r\n" + "Signature: " + sSignature,
                "UTF-8");
        //result.setResponseData("OK", "UTF-8");
        result.setSuccessful(true);
        result.setResponseMessage("Successfully performed action");
        result.setResponseCodeOK(); // 200 code
    } catch (Exception e) {
        java.io.StringWriter stringWriter = new java.io.StringWriter();
        e.printStackTrace(new java.io.PrintWriter(stringWriter));
        result.setResponseData(stringWriter.toString(), "UTF-8");
        result.setDataType(org.apache.jmeter.samplers.SampleResult.TEXT);
        result.setResponseCode("500");
    }
    return result;
}

From source file:ru.pflb.samlsampler.SamlSampler.java

private static String deflateAndBase64encode(String xml) throws IOException {
    Deflater deflater = new Deflater(Deflater.DEFLATED, true);

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteArrayOutputStream, deflater);

    deflaterOutputStream.write(xml.getBytes());
    deflaterOutputStream.close();/*from w w w . ja v a2  s  .c  o m*/

    //String encoded = new BASE64Encoder().encode(byteArrayOutputStream.toByteArray());
    String encoded = new String(Base64.encode(byteArrayOutputStream.toByteArray()));
    return encoded;
}

From source file:tdunnick.jphineas.encryption.Encryptor.java

License:Open Source License

/**
 * Encrypts some data//  www .  j  av  a2 s  . c om
 * @param data to be encrypted
 * @param key to use for the encryption
 * @return base64 encoded encrypted data
 */
public String encrypt(byte[] data, Key key) {
    if ((data == null) || (key == null))
        return null;
    try {
        Cipher cipher = getCipher(Cipher.ENCRYPT_MODE, key);
        if (cipher == null)
            return null;
        // triple DES CBC block uses 8 byte pre-pended initial vector
        byte[] iv = cipher.getIV();
        if (iv != null)
            data = ByteArray.append(iv, data);
        byte[] d = cipher.doFinal(data);
        return new String(Base64.encode(d));
    } catch (Exception e) {
        Log.error("Can't encrypt with " + getTransform(key) + ": " + e.getMessage());
    }
    return null;
}

From source file:tdunnick.jphineas.mime.MimeContent.java

License:Open Source License

/**
 * Set BASIC authentication//from  w  w w  .  j  a v  a 2s .  c  om
 * TODO set digest authentication
 * 
 * @param uid - user id
 * @param password - user password
 */
public void setBasicAuth(String uid, String password) {
    if ((uid == null) || (password == null))
        return;
    byte[] encoded = Base64.encode((uid + ":" + password).getBytes());
    setHeader("Authorization", "Basic " + new String(encoded));
}

From source file:tdunnick.jphineas.mime.MimeContent.java

License:Open Source License

/**
 * Set encoding to base64 and encode the binary body
 * @param body to encode//from  ww w .  java 2s  .  com
 * @return true if successful
 */
public boolean encodeBody(byte[] body) {
    setEncoding(BASE64);
    setContentType(MimeContent.OCTET);
    setBody(new String(Base64.encode(body)));
    return false;
}

From source file:tdunnick.phinmsx.crypt.Encryptor.java

License:Open Source License

/**
 * Encrypts some data//from   ww  w  . jav  a2s .  c om
 * @param data to be encrypted
 * @param key to use for the encryption
 * @return base64 encoded encrypted data
 */
public String encrypt(byte[] data, Key key) {
    if ((data == null) || (key == null))
        return null;
    try {
        Cipher cipher = getCipher(Cipher.ENCRYPT_MODE, key);
        if (cipher == null)
            return null;
        // triple DES CBC block uses 8 byte pre-pended initial vector
        byte[] iv = cipher.getIV();
        if (iv != null)
            data = ByteArray.append(iv, data);
        byte[] d = cipher.doFinal(data);
        return new String(Base64.encode(d));
    } catch (Exception e) {
        logger.severe("Can't encrypt with " + getTransform(key) + ": " + e.getMessage());
    }
    return null;
}