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:crypto.encryptor.util.HashFunctionUtil.java

/**
 * A static method for hashing data with a chosen hash function depending on input parameters.
 * /*from www. j av  a 2  s.co  m*/
 * @param salt             the salt value
 * @param data             the data to hash
 * @param hashFunctionEnum the enum representing hash function
 * @return                 the hashed data as Base64 encoded string
 */
public static String hash(String salt, String data, HashFunctionEnum hashFunctionEnum)
        throws UnsupportedEncodingException {

    logger.debug(
            "Hashing data with key='" + salt + "', value='" + data + "', Hash function=" + hashFunctionEnum);

    if (hashFunctionEnum == null) {
        throw new IllegalArgumentException(
                "Input argument 'hashFunctionEnum' of " + "type HashFunctionEnum can't be null ");
    }

    if (unsupportedHashFunctionList.contains(hashFunctionEnum)) {
        throw new UnsupportedOperationException(
                "The hash function " + hashFunctionEnum.value() + " is not supported.");
    }

    String hashedString = null;
    if (hashFunctionEnum == HashFunctionEnum.BCRYPT) {

        hashedString = bCryptHashPassword(data, salt);

    } else {

        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance(hashFunctionEnum.value());
        } catch (Exception ex) {
            ex.printStackTrace();
            logger.error("Error hashing data by Hash function '" + hashFunctionEnum.name() + "'", ex);
            return null;
        }

        messageDigest.update(salt.getBytes());
        messageDigest.update(data.getBytes());
        byte[] hashedBytes = messageDigest.digest();

        // Use this if need to output byte as HEX encoded string. 
        //
        // The use of DatatypeConverter.printHexBinary(..) is gold, see 
        // https://stackoverflow.com/questions/9655181/how-to-convert-a-byte-array-to-a-hex-string-in-java for why.
        // return javax.xml.bind.DatatypeConverter.printHexBinary( bytesArray );

        hashedString = new String(Base64.encode(hashedBytes), UTF8);
    }

    return hashedString;
}

From source file:crypto.encryptor.util.HashFunctionUtil.java

/**
 * Return random generated salt. This should be a pretty good salt. See  
 * https://www.cigital.com/blog/proper-use-of-javas-securerandom/ for why.
 * //from  w w w  . j ava2 s. c  o  m
 * @return Base64 encoded salt for hashing data.
 * 
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws UnsupportedEncodingException 
 */
public static String getSalt()
        throws NoSuchAlgorithmException, NoSuchProviderException, UnsupportedEncodingException {
    // Always specify the exact PRNG and provider that you wish to use else may end up with weaker implementation
    // of PRNG in different platforms
    SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG", "SUN");

    byte[] saltBytes = new byte[16];

    // always call SecureRandom.nextBytes(byte[]) immediately after creating a new instance of the PRNG
    secureRandom.nextBytes(saltBytes);

    // return base64 encoded string
    return new String(Base64.encode(saltBytes), UTF8);
}

From source file:crypto.util.encription.Crypto.java

public String encrypt(String data) throws CryptoException {

    String result = null;/*from w w  w  .  j  av  a  2  s.com*/

    if (data != null) {
        cipher.init(true, key);
        byte[] b = callCipher(data.getBytes());
        result = new String(Base64.encode(b));
    } else {
        return new String(new byte[0]);
    }
    return result;
}

From source file:crypto.util.encription.Crypto.java

public String encrypt(byte[] data) throws CryptoException {

    String result = null;/* w w w . j a va2 s  . c  o m*/

    if (data.length != 0) {
        cipher.init(true, key);
        byte[] b = callCipher(data);
        result = new String(Base64.encode(b));
    } else {
        return new String(new byte[0]);
    }
    return result;
}

From source file:crypto.util.hash.Hash.java

public String generateHash(File file, Boolean replace) throws FileNotFoundException, IOException {
    String hash = null;/* w w w.  j a  v  a  2s.co m*/
    //converting file to bytes
    FileInputStream fis = null;

    fis = new FileInputStream(file);

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    byte[] buf = new byte[1024];

    for (int readNum; (readNum = fis.read(buf)) != -1;) {
        bos.write(buf, 0, readNum); //no doubt here is 0
    }

    byte[] bytes = bos.toByteArray();

    Security.addProvider(new BouncyCastleProvider());
    Digest messageDigestObj = new SHA1Digest();
    byte[] digest = new byte[messageDigestObj.getDigestSize()];
    messageDigestObj.update(bytes, 0, bytes.length);
    messageDigestObj.doFinal(digest, 0);
    hash = new String(Base64.encode(digest));

    if (replace) {
        hash = hash.replace("/", "").replace("=", "");
    }

    return hash;
}

From source file:crypto.util.hash.Hash.java

public String generateHash(String data, Boolean replace) {
    String hash = null;//from w w w  .j ava  2 s.  c o  m
    Security.addProvider(new BouncyCastleProvider());
    Digest messageDigestObj = new SHA1Digest();
    byte[] digest = new byte[messageDigestObj.getDigestSize()];
    messageDigestObj.update(data.getBytes(), 0, data.getBytes().length);
    messageDigestObj.doFinal(digest, 0);

    hash = new String(Base64.encode(digest));

    if (replace) {
        hash = hash.replace("/", "").replace("=", "");
    }

    return hash;
}

From source file:cryptochatclient.model.MessageSender.java

public void send(Message message, Session session) throws Exception {
    byte[] data;/* ww  w .ja v  a2 s  .  c om*/
    byte[] encrypted;
    switch (message.getType()) {
    case Message.EXCHANGE_PUBLIC_KEY:
        byte[] key = Base64.encode(((PublicKeyExchangeMessage) message).getKey());
        _out.writeUTF(new String(key));
        break;
    case Message.EXCHANGE_SYMMETRIC_ENCRYPTION_DATA:
        data = Message.getFullMessage(message, session);
        encrypted = Base64.encode(_provider.encryptServerMessage(data));
        _out.writeUTF(new String(encrypted));
        break;
    default:
        data = Message.getFullMessage(message, session);
        encrypted = Base64.encode(CryptoUtils.encryptData(data, session));
        _out.writeUTF(new String(encrypted));
        break;
    }
}

From source file:cybervillains.ca.ThumbprintUtil.java

License:Open Source License

/**
 * Generates a SHA1 thumbprint of a certificate for long-term mapping.
 * //from w  w  w  .  j  a v a2  s. c  o m
 * @param cert
 * @return
 * @throws CertificateEncodingException
 */
public static String getThumbprint(final X509Certificate cert) throws CertificateEncodingException {

    if (cert == null) {
        return null;
    }

    byte[] rawOctets = cert.getEncoded();

    SHA1Digest digest = new SHA1Digest();

    byte[] digestOctets = new byte[digest.getDigestSize()];

    digest.update(rawOctets, 0, rawOctets.length);

    digest.doFinal(digestOctets, 0);

    return new String(Base64.encode(digestOctets));
}

From source file:cz.muni.fi.xklinec.zipstream.Utils.java

License:Open Source License

/**
 * Computes SHA256 hash of a given file.
 * @param b// ww w .  j a  v a2  s. com
 * @return 
 */
public static String sha256(byte[] b) {
    try {
        MessageDigest sha = MessageDigest.getInstance("SHA-256");
        InputStream fis = new ByteArrayInputStream(b);
        DigestInputStream dis = new DigestInputStream(fis, sha);

        byte[] buffer = new byte[65536]; // 64kB buffer
        while (dis.read(buffer) != -1) {
        }

        byte[] hash = sha.digest();
        return new String(Base64.encode(hash));

    } catch (Exception e) {
        throw new IllegalArgumentException("Cannot compute SHA256 digest of the file", e);
    }
}

From source file:cz.muni.ics.remsig.impl.CertificateManagerImplTest.java

/**
 * /*from  w ww  . j a v a2  s  .c o  m*/
 * @param filePath to p12 file
 * @return convert through bytes and returns string
 */
public String loadPKCS12(String filePath) {
    String encodedString = null;
    try {
        byte[] bytes = Files.readAllBytes(Paths.get(filePath));
        byte[] encoded = Base64.encode(bytes);
        encodedString = new String(encoded);
    } catch (IOException ex) {

    }
    return encodedString;
}