Example usage for org.bouncycastle.crypto.params Argon2Parameters getType

List of usage examples for org.bouncycastle.crypto.params Argon2Parameters getType

Introduction

In this page you can find the example usage for org.bouncycastle.crypto.params Argon2Parameters getType.

Prototype

public int getType() 

Source Link

Usage

From source file:org.springframework.security.crypto.argon2.Argon2EncodingUtils.java

License:Apache License

/**
 * Encodes a raw Argon2-hash and its parameters into the standard Argon2-hash-string as specified in the reference
 * implementation (https://github.com/P-H-C/phc-winner-argon2/blob/master/src/encoding.c#L244):
 *
 * {@code $argon2<T>[$v=<num>]$m=<num>,t=<num>,p=<num>$<bin>$<bin>}
 *
 * where {@code <T>} is either 'd', 'id', or 'i', {@code <num>} is a decimal integer (positive,
 * fits in an 'unsigned long'), and {@code <bin>} is Base64-encoded data (no '=' padding
 * characters, no newline or whitespace).
 *
 * The last two binary chunks (encoded in Base64) are, in that order,
 * the salt and the output. If no salt has been used, the salt will be omitted.
 *
 * @param hash the raw Argon2 hash in binary format
 * @param parameters the Argon2 parameters that were used to create the hash
 * @return the encoded Argon2-hash-string as described above
 * @throws IllegalArgumentException if the Argon2Parameters are invalid
 */// ww  w.  ja  v  a 2  s.c  o m
public static String encode(byte[] hash, Argon2Parameters parameters) throws IllegalArgumentException {
    StringBuilder stringBuilder = new StringBuilder();

    switch (parameters.getType()) {
    case Argon2Parameters.ARGON2_d:
        stringBuilder.append("$argon2d");
        break;
    case Argon2Parameters.ARGON2_i:
        stringBuilder.append("$argon2i");
        break;
    case Argon2Parameters.ARGON2_id:
        stringBuilder.append("$argon2id");
        break;
    default:
        throw new IllegalArgumentException("Invalid algorithm type: " + parameters.getType());
    }
    stringBuilder.append("$v=").append(parameters.getVersion()).append("$m=").append(parameters.getMemory())
            .append(",t=").append(parameters.getIterations()).append(",p=").append(parameters.getLanes());

    if (parameters.getSalt() != null) {
        stringBuilder.append("$").append(b64encoder.encodeToString(parameters.getSalt()));
    }

    stringBuilder.append("$").append(b64encoder.encodeToString(hash));

    return stringBuilder.toString();
}