java 密码SHA-2加密,springboot-bcrypt加密

本文介绍了在SpringBoot应用中如何使用SHA-2算法生成加盐哈希密码,以及如何利用bcrypt进行自动加盐的密码加密,包括示例代码演示了整个过程。
摘要由CSDN通过智能技术生成

原理底层啥的就不说了,小白的我只注重使用


SHA-2加密


// 生成随机盐
    public static String generateSalt() {
        SecureRandom random = new SecureRandom();
        byte[] salt = new byte[16];
        random.nextBytes(salt);
        return Base64.getEncoder().encodeToString(salt);
    }

    // 哈希密码
    public static String hashPassword(String password, String salt) throws NoSuchAlgorithmException {
        String saltedPassword = new StringBuffer(salt).append(password).toString();
        // 这里可以使用SHA-224,SHA-256,SHA-384,SHA-512, 只是生成消息摘要长度,循环次数不同之外,算法基本一致
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        byte[] hashedPassword = md.digest(saltedPassword.getBytes());
        return Base64.getEncoder().encodeToString(hashedPassword);
    }

    // 验证密码
    public static boolean verifyPassword(String password, String salt, String hashedPassword) throws NoSuchAlgorithmException {
        String hashedInput = hashPassword(password, salt);
        return hashedInput.equals(hashedPassword);
    }

    public static void main(String[] args) throws NoSuchAlgorithmException {
        // 示例演示了密码哈希和加盐存储的过程
        String password = "myPassword123";
        String salt = generateSalt();
        String hashedPassword = hashPassword(password, salt);

        System.out.println("原密码: " + password);
        System.out.println("盐: " + salt);
        System.out.println("哈希后的密码: " + hashedPassword);

        // 验证密码
        boolean isValid = verifyPassword(password, salt, hashedPassword);
        System.out.println("密码验证结果: " + isValid);
    }

springboot-bcrypt加密


引入 

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

使用 

public static void main(String[] args) {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        // 加密。不需要加盐,它内部已经加盐了
        System.out.println(bCryptPasswordEncoder.encode("123456"));
        // 比对
        System.out.println(bCryptPasswordEncoder.matches("123456", "$2a$10$THlC1Z46enO4b6bjqMIQjug9ip9YFDROuCHLPOppMllgz1X3dCZ8a"));
    }

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java中常用的密码加密方法有MD5、SHA、AES等,下面分别介绍它们的使用方法。 MD5加密: MD5是一种不可逆的加密方式,将明文密码转换成一串固定长度的字符串,一般用于存储密码加密Java中可以通过java.security.MessageDigest类实现MD5加密。示例代码如下: ```java import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class MD5Util { public static String md5(String password) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); byte[] bytes = md5.digest(password.getBytes()); StringBuilder stringBuilder = new StringBuilder(); for (byte b : bytes) { int temp = b & 0xff; String hexString = Integer.toHexString(temp); if (hexString.length() == 1) { stringBuilder.append("0").append(hexString); } else { stringBuilder.append(hexString); } } return stringBuilder.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; } public static void main(String[] args) { String password = "123456"; String encryptedPassword = md5(password); System.out.println(encryptedPassword); } } ``` SHA加密SHA也是一种不可逆的加密方式,与MD5类似,但SHA更安全。Java中可以通过java.security.MessageDigest类实现SHA加密。示例代码如下: ```java import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class SHAUtil { public static String sha(String password) { try { MessageDigest sha = MessageDigest.getInstance("SHA"); byte[] bytes = sha.digest(password.getBytes()); StringBuilder stringBuilder = new StringBuilder(); for (byte b : bytes) { int temp = b & 0xff; String hexString = Integer.toHexString(temp); if (hexString.length() == 1) { stringBuilder.append("0").append(hexString); } else { stringBuilder.append(hexString); } } return stringBuilder.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; } public static void main(String[] args) { String password = "123456"; String encryptedPassword = sha(password); System.out.println(encryptedPassword); } } ``` AES加密: AES是一种对称加密方式,即加密和解密使用相同的密钥。Java中可以通过javax.crypto.Cipher类实现AES加密。示例代码如下: ```java import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.Base64; public class AESUtil { private static final String AES = "AES"; public static String encrypt(String content, String password) { try { KeyGenerator keyGenerator = KeyGenerator.getInstance(AES); SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG"); secureRandom.setSeed(password.getBytes()); keyGenerator.init(128, secureRandom); SecretKey secretKey = keyGenerator.generateKey(); byte[] enCodeFormat = secretKey.getEncoded(); SecretKeySpec key = new SecretKeySpec(enCodeFormat, AES); Cipher cipher = Cipher.getInstance(AES);// 创建密码器 byte[] byteContent = content.getBytes("utf-8"); cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化 byte[] result = cipher.doFinal(byteContent); return Base64.getEncoder().encodeToString(result);// 加密 } catch (Exception e) { e.printStackTrace(); } return null; } public static String decrypt(String content, String password) { try { KeyGenerator keyGenerator = KeyGenerator.getInstance(AES); SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG"); secureRandom.setSeed(password.getBytes()); keyGenerator.init(128, secureRandom); SecretKey secretKey = keyGenerator.generateKey(); byte[] enCodeFormat = secretKey.getEncoded(); SecretKeySpec key = new SecretKeySpec(enCodeFormat, AES); Cipher cipher = Cipher.getInstance(AES);// 创建密码器 cipher.init(Cipher.DECRYPT_MODE, key);// 初始化 byte[] result = cipher.doFinal(Base64.getDecoder().decode(content)); return new String(result, "utf-8"); } catch (Exception e) { e.printStackTrace(); } return null; } public static void main(String[] args) { String content = "123456"; String password = "password"; String encryptedContent = encrypt(content, password); System.out.println("加密后:" + encryptedContent); String decryptedContent = decrypt(encryptedContent, password); System.out.println("解密后:" + decryptedContent); } } ``` Spring Boot中可以使用Spring Security提供的PasswordEncoder接口来实现密码加密和解密。示例代码如下: ```java import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; public class PasswordUtil { public static String encode(String password) { PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); return passwordEncoder.encode(password); } public static boolean match(String password, String encodedPassword) { PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); return passwordEncoder.matches(password, encodedPassword); } public static void main(String[] args) { String password = "123456"; String encodedPassword = encode(password); System.out.println("加密后:" + encodedPassword); boolean match = match(password, encodedPassword); System.out.println("匹配结果:" + match); } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值