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:frost.crypt.FrostCrypt.java

License:Open Source License

/**
 * Generate a new RSA 1024 bit key pair.
 * @returns String[0] is private key; String[1] is public key
 *//*from w w w . j av a2 s . c  om*/
public synchronized String[] generateKeys() {

    RSAKeyPairGenerator keygen = new RSAKeyPairGenerator();
    keygen.init(new RSAKeyGenerationParameters(
            new BigInteger("3490529510847650949147849619903898133417764638493387843990820577"),
            getSecureRandom(), 1024, 80));
    //this big integer is the winner of some competition as far as I remember

    AsymmetricCipherKeyPair keys = keygen.generateKeyPair();

    //extract the keys
    RSAKeyParameters pubKey = (RSAKeyParameters) keys.getPublic();
    RSAPrivateCrtKeyParameters privKey = (RSAPrivateCrtKeyParameters) keys.getPrivate();

    //the return value
    String[] result = new String[2];
    StringBuffer temp = new StringBuffer();

    //create the keys
    temp.append(new String(Base64.encode(pubKey.getExponent().toByteArray())));
    temp.append(":");
    temp.append(new String(Base64.encode(pubKey.getModulus().toByteArray())));
    result[1] = temp.toString(); // public key

    //rince and repeat, this time exactly the way its done in the constructor
    temp = new StringBuffer();
    temp.append(new String(Base64.encode(privKey.getModulus().toByteArray())));
    temp.append(":");
    temp.append(new String(Base64.encode(privKey.getPublicExponent().toByteArray())));
    temp.append(":");
    temp.append(new String(Base64.encode(privKey.getExponent().toByteArray())));
    temp.append(":");
    temp.append(new String(Base64.encode(privKey.getP().toByteArray())));
    temp.append(":");
    temp.append(new String(Base64.encode(privKey.getQ().toByteArray())));
    temp.append(":");
    temp.append(new String(Base64.encode(privKey.getDP().toByteArray())));
    temp.append(":");
    temp.append(new String(Base64.encode(privKey.getDQ().toByteArray())));
    temp.append(":");
    temp.append(new String(Base64.encode(privKey.getQInv().toByteArray())));
    result[0] = temp.toString(); // private key

    return result;
}

From source file:frost.crypt.FrostCrypt.java

License:Open Source License

/**
 * Computes the SHA-1 checksum of given message.
 *///from  ww w. ja v  a2  s. c  om
public synchronized String digest(String message) {
    try {
        SHA1Digest stomach = new SHA1Digest();
        stomach.reset();
        byte[] food = message.getBytes("UTF-8");
        stomach.update(food, 0, food.length);
        byte[] poop = new byte[64];
        stomach.doFinal(poop, 0);
        return (new String(Base64.encode(poop))).substring(0, 27);
    } catch (UnsupportedEncodingException ex) {
        Logger.error(this, "UTF-8 encoding is not supported : " + ex.toString());
    }
    return null;
}

From source file:frost.crypt.FrostCrypt.java

License:Open Source License

/**
 * Computes the SHA-1 checksum of given file.
 *//*w w w  .ja  v  a2 s .  c  o  m*/
public synchronized String digest(File file) {
    SHA1Digest stomach = new SHA1Digest();
    byte[] poop = new byte[64];
    FileChannel chan = null;
    try {
        chan = (new FileInputStream(file)).getChannel();
    } catch (IOException e) {
        Logger.error(this, "Exception thrown in digest(File file): " + e.toString());
    }
    byte[] temp = new byte[4 * 1024];
    ByteBuffer _temp = ByteBuffer.wrap(temp);
    try {
        while (true) {
            //if (y >= file.length()) break;
            //if (y > file.length()) y = file.length();
            int pos = _temp.position();
            int read = chan.read(_temp);
            if (read == -1)
                break;
            stomach.update(temp, pos, read);
            if (_temp.remaining() == 0)
                _temp.position(0);
        }
        chan.close();
    } catch (IOException e) {
        Logger.error(this, "Exception thrown in digest(File file): " + e.toString());
    }
    stomach.doFinal(poop, 0);
    return (new String(Base64.encode(poop))).substring(0, 27);
}

From source file:frost.crypt.FrostCrypt.java

License:Open Source License

public synchronized String encrypt(String what, String publicKey) {
    try {//from w w w.  j ava 2s.  c  o m
        byte[] whatBytes = what.getBytes("UTF-8");
        byte[] encryptedBytes = encrypt(whatBytes, publicKey);
        String result = new String(Base64.encode(encryptedBytes), "ISO-8859-1");
        return result;
    } catch (UnsupportedEncodingException ex) {
        Logger.error(this, "UTF-8 encoding is not supported: " + ex.toString());
    }
    return null;
}

From source file:frost.crypt.FrostCrypt.java

License:Open Source License

public synchronized String detachedSign(byte[] message, String key) {

    StringTokenizer keycutter = new StringTokenizer(key, ":");
    RSAPrivateCrtKeyParameters privKey = new RSAPrivateCrtKeyParameters(
            new BigInteger(Base64.decode(keycutter.nextToken())),
            new BigInteger(Base64.decode(keycutter.nextToken())),
            new BigInteger(Base64.decode(keycutter.nextToken())),
            new BigInteger(Base64.decode(keycutter.nextToken())),
            new BigInteger(Base64.decode(keycutter.nextToken())),
            new BigInteger(Base64.decode(keycutter.nextToken())),
            new BigInteger(Base64.decode(keycutter.nextToken())),
            new BigInteger(Base64.decode(keycutter.nextToken())));

    signer.init(true, privKey);/*from www . j a  v a2s .co m*/
    signer.update(message, 0, message.length);

    byte[] signature = null;
    try {
        signature = signer.generateSignature();
    } catch (CryptoException e) {
        Logger.error(this, "Exception thrown in detachedSign(String message, String key): " + e.toString());
    }
    signer.reset();
    try {
        String result = new String(Base64.encode(signature), "ISO-8859-1");
        return result;
    } catch (UnsupportedEncodingException ex) {
        Logger.error(this, "ISO-8859-1 encoding is not supported: " + ex.toString());
    }
    return null;
}

From source file:frost.crypt.FrostCrypt.java

License:Open Source License

public String encode64(String what) {
    try {/*from w w  w . j  a  v  a  2  s  . c  o m*/
        byte[] whatBytes = what.getBytes("UTF-8");
        return new String(Base64.encode(whatBytes), "ISO-8859-1");
    } catch (UnsupportedEncodingException ex) {
        Logger.error(this, "UTF-8 or ISO-8859-1 encoding is not supported: " + ex.toString());
    }
    return null;
}

From source file:grantedbyme.CryptoUtil.java

License:Open Source License

/**
 * JSON object encryptor helper//from  ww w  .ja  va2 s . c om
 *
 * @param requestBody
 * @param serverPublicKey
 * @param privateKey
 * @param publicHash
 * @return
 */
public static JSONObject encryptAndSign(JSONObject requestBody, PublicKey serverPublicKey,
        PrivateKey privateKey, String publicHash) {
    //if (BuildConfig.DEBUG) Log.d(TAG, "encryptAndSign: " + requestBody);
    // Convert JSON String to Bytes
    byte[] plainBytes = requestBody.toString().getBytes();
    // AES cipher
    byte[] cipherKey = randomBytes(16);
    byte[] cipherIv = randomBytes(16);
    byte[] cipherBytes;
    byte[] cipherSignature;
    String cipherText;
    JSONObject cipherJSON;
    // RSA payload
    byte[] payloadBytes;
    String payloadText;
    // RSA signature
    byte[] signatureBytes;
    String signatureText;
    // AES encrypt -> RSA encrypt -> RSA sign
    try {
        if (plainBytes.length < 215) {
            cipherText = null;
            final Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding", PROVIDER);
            cipher.init(Cipher.ENCRYPT_MODE, serverPublicKey);
            payloadBytes = cipher.doFinal(plainBytes);
            payloadText = new String(Base64.encode(payloadBytes), "UTF-8");
            // Generate RSA signature
            final Signature s = Signature.getInstance("SHA512WITHRSAANDMGF1", PROVIDER);
            //s.setParameter(new PSSParameterSpec("SHA-512", "MGF1", MGF1ParameterSpec.SHA512, 64, 1));
            s.initSign(privateKey);
            s.update(plainBytes);
            signatureBytes = s.sign();
            signatureText = new String(Base64.encode(signatureBytes), "UTF-8");
        } else {
            cipherBytes = crypt(plainBytes, cipherKey, cipherIv, Cipher.ENCRYPT_MODE);
            cipherText = new String(Base64.encode(cipherBytes), "UTF-8");
            // Sign using HMAC
            final Mac hmac = Mac.getInstance("HmacSHA256", PROVIDER);
            final SecretKeySpec keySpec = new SecretKeySpec(cipherKey, "HmacSHA256");
            hmac.init(keySpec);
            cipherSignature = hmac.doFinal(plainBytes);
            // Wrap AES cipher data into JSON
            Map<String, Object> cipherParams = new HashMap<>();
            cipherParams.put("cipher_key", new String(Base64.encode(cipherKey), "UTF-8"));
            cipherParams.put("cipher_iv", new String(Base64.encode(cipherIv), "UTF-8"));
            cipherParams.put("signature", new String(Base64.encode(cipherSignature), "UTF-8"));
            Long timestamp = System.currentTimeMillis() / 1000L;
            cipherParams.put("timestamp", timestamp);
            cipherJSON = new JSONObject(cipherParams);
            // System.out.println(cipherJSON.toJSONString());
            final Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding", PROVIDER);
            cipher.init(Cipher.ENCRYPT_MODE, serverPublicKey);
            payloadBytes = cipher.doFinal(cipherJSON.toString().getBytes());
            payloadText = new String(Base64.encode(payloadBytes), "UTF-8");
            // Generate RSA signature
            final Signature s = Signature.getInstance("SHA512WITHRSAANDMGF1", PROVIDER);
            //s.setParameter(new PSSParameterSpec("SHA-512", "MGF1", MGF1ParameterSpec.SHA512, 64, 1));
            s.initSign(privateKey);
            s.update(cipherJSON.toString().getBytes());
            signatureBytes = s.sign();
            signatureText = new String(Base64.encode(signatureBytes), "UTF-8");
        }
    } catch (Exception e) {
        throw new RuntimeException("encryptAndSign failed", e);
    }
    // collect
    Map<String, Object> params = new HashMap<>();
    params.put("payload", payloadText);
    params.put("signature", signatureText);
    if (cipherText != null) {
        params.put("message", cipherText);
    }
    params.put("public_hash", publicHash);
    // return
    return new JSONObject(params);
}

From source file:hk.hku.cecid.edi.as2.module.test.IncomingMessageProcessorTest.java

License:Open Source License

private String calculateMIC(MimeBodyPart bodyPart) throws Exception {
    // By default, MIC calculate with Headers
    ByteArrayOutputStream contentBAOS = new ByteArrayOutputStream();
    bodyPart.writeTo(contentBAOS);/*from  w  w  w. j av  a2  s .co  m*/
    byte[] content = (contentBAOS.toByteArray());

    MessageDigest md = MessageDigest.getInstance(SMIMESignedGenerator.DIGEST_SHA1, "BC");
    md.update(content);

    byte[] digest = md.digest();
    String digestString = new String(Base64.encode(digest));
    return digestString + ", " + DispositionNotificationOption.SIGNED_RECEIPT_MICALG_SHA1;
}

From source file:hk.hku.cecid.edi.as2.module.test.OutgoingMessageProcessorTest.java

License:Open Source License

private String calculateMIC(byte[] content) throws Exception {
    String digestAlg = (partnershipDVO.getMicAlgorithm() == null ? PartnershipDVO.ALG_MIC_SHA1
            : partnershipDVO.getMicAlgorithm());
    MessageDigest md = MessageDigest.getInstance(digestAlg, "BC");
    md.update(content);/*www .j  a va  2  s.  c o m*/

    byte[] digest = md.digest();
    String digestString = new String(Base64.encode(digest));
    return digestString + ", " + partnershipDVO.getMicAlgorithm();
}

From source file:hk.hku.cecid.piazza.commons.security.SMimeMessage.java

License:Open Source License

/**
 * Digests the encapsulated MIME body part. 
 * /* w  ww.j  a  v a  2s .  c o m*/
 * @param digestAlg digest algorithm.
 * @param isHeadersIncluded true if the digest should be computed on both 
 *        the headers and the content of the encapsulated body part.
 * @return the digested value in Base 64 format.
 * @throws SMimeException if unable to compute the digest value.
 */
public String digest(String digestAlg, boolean isHeadersIncluded) throws SMimeException {
    try {
        if (digestAlg == null) {
            digestAlg = SMimeMessage.DIGEST_ALG_SHA1;
        }

        MessageDigest md = MessageDigest.getInstance(digestAlg, "BC");

        InputStream ins;

        if (isHeadersIncluded) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bodyPart.writeTo(baos);
            byte[] data = baos.toByteArray();
            ins = canonicalize(data);
        } else {
            ins = bodyPart.getInputStream();
        }

        DigestInputStream digIns = new DigestInputStream(ins, md);

        byte[] buf = new byte[1024];
        while (digIns.read(buf) >= 0) {
        }

        byte[] digest = digIns.getMessageDigest().digest();
        String digestString = new String(Base64.encode(digest));
        return digestString;
    } catch (Exception e) {
        throw new SMimeException("Unable to compute message digest", e);
    }
}