public Hash parse()

in crypto/hash/src/main/java/org/apache/shiro/crypto/hash/format/Shiro1CryptFormat.java [134:183]


    public Hash parse(final String formatted) {
        if (formatted == null) {
            return null;
        }
        if (!formatted.startsWith(MCF_PREFIX)) {
            //TODO create a HashFormatException class
            String msg = "The argument is not a valid '" + ID + "' formatted hash.";
            throw new IllegalArgumentException(msg);
        }

        String suffix = formatted.substring(MCF_PREFIX.length());
        String[] parts = suffix.split("\\$");

        final String algorithmName = parts[0];
        if (!new SimpleHashProvider().getImplementedAlgorithms().contains(algorithmName)) {
            throw new UnsupportedOperationException("Algorithm " + algorithmName + " is not supported in shiro1 format.");
        }

        //last part is always the digest/checksum, Base64-encoded:
        int i = parts.length - 1;
        String digestBase64 = parts[i--];
        //second-to-last part is always the salt, Base64-encoded:
        String saltBase64 = parts[i--];
        String iterationsString = parts[i--];

        byte[] digest = Base64.decode(digestBase64);
        ByteSource salt;

        if (StringUtils.hasLength(saltBase64)) {
            byte[] saltBytes = Base64.decode(saltBase64);
            salt = ByteSource.Util.bytes(saltBytes);
        } else {
            salt = ByteSource.Util.bytes(new byte[0]);
        }

        int iterations;
        try {
            iterations = Integer.parseInt(iterationsString);
        } catch (NumberFormatException e) {
            String msg = "Unable to parse formatted hash string: " + formatted;
            throw new IllegalArgumentException(msg, e);
        }

        SimpleHash hash = new SimpleHash(algorithmName);
        hash.setBytes(digest);
        hash.setSalt(salt);
        hash.setIterations(iterations);

        return hash;
    }