Java常见的加密算法

Java常见的加密算法

在计算机科学和信息安全领域,加密算法是用于将数据转换为不可读形式的技术,以确保数据的机密性和安全性。

这里我提供几种常见的加密算法:

  1. 对称加密算法 - AES (Advanced Encryption Standard)
  2. 非对称加密算法 - RSA (Rivest-Shamir-Adleman)
  3. 散列函数 - SHA-256 (Secure Hash Algorithm 256-bit)
  4. 消息认证码 (MAC) - HMAC (Hash-based Message Authentication Code) 。
  5. 数字签名 - DSA (Digital Signature Algorithm)
  6. MD5 (Message Digest Algorithm 5) 散列函数
  7. Base64 编码
  8. Blowfish 对称密钥分组加密算法

1、对称加密算法 - AES (Advanced Encryption Standard)

AES是一种对称加密算法,它使用相同的密钥进行加密和解密。它广泛用于保护敏感数据的机密性,如网络通信和数据存储。AES具有高度的安全性和性能,是目前最常用的对称加密算法之一。
示例代码:

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class AESExample {
    private static final String KEY = "ThisIsASecretKey"; // 16, 24, or 32 bytes

    public static String encrypt(String plainText) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(KEY.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    public static String decrypt(String encryptedText) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(KEY.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
        return new String(decryptedBytes);
    }

    public static void main(String[] args) throws Exception {
        String originalText = "Hello, this is a secret message!";
        String encryptedText = encrypt(originalText);
        System.out.println("Encrypted Text: " + encryptedText);
        String decryptedText = decrypt(encryptedText);
        System.out.println("Decrypted Text: " + decryptedText);
    }
}

2、非对称加密算法 - RSA (Rivest-Shamir-Adleman)

RSA是一种非对称加密算法,使用一对密钥,即公钥和私钥。公钥用于加密数据,私钥用于解密数据。RSA算法在数字签名和密钥交换等领域广泛应用。
示例代码:

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Base64;

public class RSAExample {
    public static String encrypt(String plainText, PublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    public static String decrypt(String encryptedText, PrivateKey privateKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
        return new String(decryptedBytes);
    }

    public static void main(String[] args) throws Exception {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(2048);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();

        String originalText = "Hello, this is a secret message!";
        String encryptedText = encrypt(originalText, publicKey);
        System.out.println("Encrypted Text: " + encryptedText);
        String decryptedText = decrypt(encryptedText, privateKey);
        System.out.println("Decrypted Text: " + decryptedText);
    }
}

3、散列函数 - SHA-256 (Secure Hash Algorithm 256-bit)

SHA-256是一种散列函数,将输入数据转换为256位的哈希值。它是不可逆的,即无法从哈希值还原原始数据。SHA-256广泛用于验证数据完整性,密码存储等场景。
示例代码:

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

public class SHA256Example {
    public static String hash(String input) throws Exception {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] hashBytes = digest.digest(input.getBytes(StandardCharsets.UTF_8));
        StringBuilder hexString = new StringBuilder();
        for (byte hashByte : hashBytes) {
            String hex = Integer.toHexString(0xff & hashByte);
            if (hex.length() == 1) hexString.append('0');
            hexString.append(hex);
        }
        return hexString.toString();
    }

    public static void main(String[] args) throws Exception {
        String data = "Hello, this is some data to hash!";
        String hashedData = hash(data);
        System.out.println("Hashed Data: " + hashedData);
    }
}

4、消息认证码 (MAC) - HMAC (Hash-based Message Authentication Code)

HMAC是一种基于散列函数的消息认证码,通过在消息上应用密钥生成认证码,用于验证消息的完整性和真实性。常用于数据完整性检查和身份验证。
示例代码:

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class HMACExample {
    private static final String KEY = "ThisIsASecretKey"; // Secret Key

    public static String generateHMAC(String data) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(KEY.getBytes(), "HmacSHA256");
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(secretKeySpec);
        byte[] hmacBytes = mac.doFinal(data.getBytes());
        return Base64.getEncoder().encodeToString(hmacBytes);
    }

    public static void main(String[] args) throws Exception {
        String data = "Hello, this is some data to authenticate!";
        String hmac = generateHMAC(data);
        System.out.println("HMAC: " + hmac);
    }
}

5、数字签名 - DSA (Digital Signature Algorithm)

DSA是一种用于数字签名的非对称加密算法。它允许私钥持有者签署消息,以便公众可以使用公钥验证签名的有效性,确保数据的来源和完整性。
示例代码:

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.util.Base64;

public class DSAExample {
    public static String signData(String data, PrivateKey privateKey) throws Exception {
        Signature signature = Signature.getInstance("SHA256withDSA");
        signature.initSign(privateKey);
        signature.update(data.getBytes());
        byte[] signedBytes = signature.sign();
        return Base64.getEncoder().encodeToString(signedBytes);
    }

    public static boolean verifySignature(String data, String signature, PublicKey publicKey) throws Exception {
        Signature verifier = Signature.getInstance("SHA256withDSA");
        verifier.initVerify(publicKey);
        verifier.update(data.getBytes());
        byte[] signatureBytes = Base64.getDecoder().decode(signature);
        return verifier.verify(signatureBytes);
    }

    public static void main(String[] args) throws Exception {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("DSA");
        keyPairGenerator.initialize(1024);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();

        String data = "Hello, this is some data to sign and verify!";
        String signature = signData(data, privateKey);

        boolean isSignatureValid = verifySignature(data, signature, publicKey);
        System.out.println("Is Signature Valid? " + isSignatureValid);
    }
}

6、MD5 (Message Digest Algorithm 5) 散列函数

MD5算法将输入数据分成512位的块,然后对每个块进行一系列变换操作,最终生成128位的哈希值。MD5算法在密码存储和数据完整性检查等场景曾经广泛应用,但由于其不安全性,现已不推荐用于密码存储。
示例代码:

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Example {
    public static String getMD5(String input) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] messageDigest = md.digest(input.getBytes());
        BigInteger no = new BigInteger(1, messageDigest);
        StringBuilder hashText = new StringBuilder(no.toString(16));
        while (hashText.length() < 32) {
            hashText.insert(0, "0");
        }
        return hashText.toString();
    }

    public static void main(String[] args) {
        try {
            String data = "Hello, this is some data to hash using MD5!";
            String hashedData = getMD5(data);
            System.out.println("Hashed Data: " + hashedData);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }
}

7、Base64 编码

Base64编码并不是加密算法,而是一种编码方式。它将二进制数据转换为文本字符串,常用于在网络传输中传递二进制数据,如图片、音频等。Base64编码后的数据可以安全地在文本格式中传输,但不提供加密功能。
示例代码:

import java.util.Base64;

public class Base64Example {
    public static String encode(String data) {
        byte[] encodedBytes = Base64.getEncoder().encode(data.getBytes());
        return new String(encodedBytes);
    }

    public static String decode(String encodedData) {
        byte[] decodedBytes = Base64.getDecoder().decode(encodedData);
        return new String(decodedBytes);
    }

    public static void main(String[] args) {
        String originalData = "Hello, this is some data to encode using Base64!";
        String encodedData = encode(originalData);
        System.out.println("Encoded Data: " + encodedData);
        String decodedData = decode(encodedData);
        System.out.println("Decoded Data: " + decodedData);
    }
}

8、Blowfish 对称密钥分组加密算法

Blowfish是一种对称密钥分组加密算法,广泛应用于数据加密和保护领域。它是一种快速、高效的算法,支持变长密钥(32位到448位)。Blowfish具有较高的安全性和可靠性。
示例代码:

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class BlowfishExample {
    private static final String KEY = "ThisIsASecretBlowfishKey"; // 16 to 56 bytes

    public static String encrypt(String data) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(KEY.getBytes(), "Blowfish");
        Cipher cipher = Cipher.getInstance("Blowfish");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedBytes = cipher.doFinal(data.getBytes());
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    public static String decrypt(String encryptedData) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(KEY.getBytes(), "Blowfish");
        Cipher cipher = Cipher.getInstance("Blowfish");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
        return new String(decryptedBytes);
    }

    public static void main(String[] args) throws Exception {
        String originalData = "Hello, this is some data to encrypt using Blowfish!";
        String encryptedData = encrypt(originalData);
        System.out.println("Encrypted Data: " + encryptedData);
        String decryptedData = decrypt(encryptedData);
        System.out.println("Decrypted Data: " + decryptedData);
    }
}

这些算法在不同的场景中被广泛使用,例如保护网络通信、数据存储、数字签名和数字证书等。需要根据具体需求和安全要求选择合适的加密算法。请注意,安全性和保密性在加密算法中非常重要,因此对密钥的管理和使用要特别谨慎。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Rosinm

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值