📜  Java的加密哈希函数(1)

📅  最后修改于: 2023-12-03 15:32:04.778000             🧑  作者: Mango

Java的加密哈希函数

哈希函数是一种将任意大小的数据映射到固定大小散列值的函数。它们常用于密码学和数据完整性检查(数据保护)。Java提供了一组标准API来执行哈希功能,这些API可以通过Java Cryptography Extension (JCE)包提供。

哈希函数类型

Java提供了三种类型的哈希函数:消息摘要、密码散列和密钥散列。

消息摘要

消息摘要是一种将输入数据转换为固定长度哈希值的算法。Java提供了几个算法来计算消息摘要,包括MD5、SHA-1和SHA-256等。

MD5:

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5HashingExample {

    public static void main(String[] args) throws NoSuchAlgorithmException {
        String input = "This is a message to hash";
        MessageDigest md5 = MessageDigest.getInstance("MD5");

        byte[] inputBytes = input.getBytes();
        byte[] hashBytes = md5.digest(inputBytes);

        StringBuilder sb = new StringBuilder();
        for (byte b : hashBytes) {
            sb.append(String.format("%02x", b));
        }
        System.out.println(sb.toString());
    }
}

SHA-1:

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class SHA1HashingExample {

    public static void main(String[] args) throws NoSuchAlgorithmException {
        String input = "This is a message to hash";
        MessageDigest sha1 = MessageDigest.getInstance("SHA-1");

        byte[] inputBytes = input.getBytes();
        byte[] hashBytes = sha1.digest(inputBytes);

        StringBuilder sb = new StringBuilder();
        for (byte b : hashBytes) {
            sb.append(String.format("%02x", b));
        }
        System.out.println(sb.toString());
    }
}

SHA-256:

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class SHA256HashingExample {

    public static void main(String[] args) throws NoSuchAlgorithmException {
        String input = "This is a message to hash";
        MessageDigest sha256 = MessageDigest.getInstance("SHA-256");

        byte[] inputBytes = input.getBytes();
        byte[] hashBytes = sha256.digest(inputBytes);

        StringBuilder sb = new StringBuilder();
        for (byte b : hashBytes) {
            sb.append(String.format("%02x", b));
        }
        System.out.println(sb.toString());
    }
}
密码散列

密码散列是一种哈希函数,用于存储用户密码,以防止明文密码泄露。Java提供了两个算法用于密码散列:PBKDF2和BCrypt。

PBKDF2:

import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Arrays;
import java.util.Base64;

public class PBKDF2HashingExample {

    public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException {
        String password = "password123";
        int iterations = 10000;
        int keyLength = 128; // bits

        byte[] salt = new byte[16];
        SecureRandom random = new SecureRandom();
        random.nextBytes(salt);

        PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt, iterations, keyLength);
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        byte[] hash = factory.generateSecret(spec).getEncoded();

        // Store hash and salt
        String storedPassword = Base64.getEncoder().encodeToString(hash);
        String storedSalt = Base64.getEncoder().encodeToString(salt);

        System.out.println("Stored Password: " + storedPassword);
        System.out.println("Stored Salt: " + storedSalt);

        // Validate password
        String inputPassword = "password123";
        byte[] inputSalt = Base64.getDecoder().decode(storedSalt);

        PBEKeySpec inputSpec = new PBEKeySpec(inputPassword.toCharArray(), inputSalt, iterations, keyLength);
        byte[] inputHash = factory.generateSecret(inputSpec).getEncoded();

        boolean isValid = Arrays.equals(hash, inputHash);
        System.out.println("Is Valid: " + isValid);
    }
}

BCrypt:

import org.mindrot.jbcrypt.BCrypt;

public class BCryptHashingExample {

    public static void main(String[] args) {
        String password = "password123";
        String hashedPassword = BCrypt.hashpw(password, BCrypt.gensalt());

        // Store hashed password
        System.out.println("Stored Password: " + hashedPassword);

        // Validate password
        String inputPassword = "password123";
        boolean isValid = BCrypt.checkpw(inputPassword, hashedPassword);
        System.out.println("Is Valid: " + isValid);
    }
}
密钥散列

密钥散列是一种哈希函数,用于使用密钥对数据进行加密和解密。Java提供了几个算法来计算密钥散列,包括HmacSHA1和HmacSHA256等。

HmacSHA1:

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

public class HmacSHA1HashingExample {

    public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException {
        String message = "This is a message to hash";
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        SecretKey secretKey = keyGen.generateKey();

        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(secretKey);

        byte[] hashBytes = mac.doFinal(message.getBytes());
        String hash = Base64.getEncoder().encodeToString(hashBytes);

        System.out.println(hash);
    }
}

HmacSHA256:

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

public class HmacSHA256HashingExample {

    public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException {
        String message = "This is a message to hash";
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        SecretKey secretKey = keyGen.generateKey();

        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(secretKey);

        byte[] hashBytes = mac.doFinal(message.getBytes());
        String hash = Base64.getEncoder().encodeToString(hashBytes);

        System.out.println(hash);
    }
}
结论

Java提供了一个强大的API来执行哈希功能。使用这些API,可以轻松地实现密码散列、消息摘要和密钥散列等各种哈希算法。选择正确的哈希函数对于确保数据安全和完整性至关重要。