欢迎访问宙启技术站
智能推送

Java加密和解密函数:MD5、RSA、AES、DES算法

发布时间:2023-05-31 08:51:14

Java是一种广泛应用的编程语言,拥有良好的跨平台性能和高效的安全性能,在加密和解密方面也有着非常成熟的算法支持,包括MD5、RSA、AES、DES等常用算法。下面将分别介绍这四个加密和解密函数的实现方式。

1. MD5算法

MD5是一种单向加密算法,常用于数据的完整性验证和密码加密。Java中提供了MessageDigest类来实现MD5加密。其基本使用方式如下:

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

public class MD5Utils {

    /**
     * 获取MD5加密后的内容
     *
     * @param content 需要加密的内容
     * @return MD5加密后的内容
     */
    public static String getMD5(String content) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] bytes = md.digest(content.getBytes());
            StringBuffer sb = new StringBuffer();
            for (byte b : bytes) {
                sb.append(Integer.toHexString((b & 0xFF) | 0x100).substring(1, 3));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
}

2. RSA算法

RSA是一种公钥加密算法,可以用于数据的加密和解密。Java中提供了KeyPairGenerator类来生成公钥和私钥,Cipher类来进行加密和解密。其基本使用方式如下:

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.Cipher;

public class RSAUtils {

    private static final String RSA = "RSA";

    /**
     * 生成公钥和私钥
     *
     * @throws Exception
     */
    public static KeyPair getKeyPair() throws Exception {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(RSA);
        keyPairGenerator.initialize(512);
        return keyPairGenerator.generateKeyPair();
    }

    /**
     * 获取公钥
     *
     * @param keyPair 密钥对
     * @return 公钥字符串
     */
    public static String getPublicKey(KeyPair keyPair) {
        PublicKey publicKey = keyPair.getPublic();
        return Base64.getEncoder().encodeToString(publicKey.getEncoded());
    }

    /**
     * 获取私钥
     *
     * @param keyPair 密钥对
     * @return 私钥字符串
     */
    public static String getPrivateKey(KeyPair keyPair) {
        PrivateKey privateKey = keyPair.getPrivate();
        return Base64.getEncoder().encodeToString(privateKey.getEncoded());
    }

    /**
     * RSA加密
     *
     * @param content   待加密内容
     * @param publicKey 公钥
     * @return 加密结果
     */
    public static String encryptRSA(String content, String publicKey) {
        try {
            byte[] decoded = Base64.getDecoder().decode(publicKey);
            PublicKey pubKey = KeyFactory.getInstance(RSA).generatePublic(new X509EncodedKeySpec(decoded));
            Cipher cipher = Cipher.getInstance(RSA);
            cipher.init(Cipher.ENCRYPT_MODE, pubKey);
            byte[] bytes = cipher.doFinal(content.getBytes());
            return Base64.getEncoder().encodeToString(bytes);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * RSA解密
     *
     * @param content    待解密内容
     * @param privateKey 私钥
     * @return 解密结果
     */
    public static String decryptRSA(String content, String privateKey) {
        try {
            byte[] byteContent = Base64.getDecoder().decode(content);
            byte[] decoded = Base64.getDecoder().decode(privateKey);
            PrivateKey priKey = KeyFactory.getInstance(RSA).generatePrivate(new PKCS8EncodedKeySpec(decoded));
            Cipher cipher = Cipher.getInstance(RSA);
            cipher.init(Cipher.DECRYPT_MODE, priKey);
            byte[] bytes = cipher.doFinal(byteContent);
            return new String(bytes);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

3. AES算法

AES是一种对称加密算法,可以用于数据的加密和解密。Java中提供了KeyGenerator类来生成密钥,Cipher类来进行加密和解密。其基本使用方式如下:

import java.security.Key;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;

public class AESUtils {
    
    private static final String AES = "AES";
    
    /**
     * 生成随机密钥
     * @return AES密钥
     * @throws Exception
     */
    public static String generateAESKey() throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(AES);
        keyGenerator.init(128);
        Key key = keyGenerator.generateKey();
        return Base64.getEncoder().encodeToString(key.getEncoded());
    }
    
    /**
     * AES加密
     * @param content 待加密内容
     * @param key AES密钥
     * @return 加密结果
     * @throws Exception
     */
    public static String encryptAES(String content, String key) throws Exception {
        Key secretKey = new javax.crypto.spec.SecretKeySpec(Base64.getDecoder().decode(key), AES);
        Cipher cipher = Cipher.getInstance(AES);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] bytes = cipher.doFinal(content.getBytes());
        return Base64.getEncoder().encodeToString(bytes);
    }
    
    /**
     * AES解密
     * @param content 待解密内容
     * @param key AES密钥
     * @return 解密结果
     * @throws Exception
     */
    public static String decryptAES(String content, String key) throws Exception {
        Key secretKey = new javax.crypto.spec.SecretKeySpec(Base64.getDecoder().decode(key), AES);
        Cipher cipher = Cipher.getInstance(AES);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] byteContent = Base64.getDecoder().decode(content);
        byte[] bytes = cipher.doFinal(byteContent);
        return new String(bytes);
    }
}

4. DES算法

DES是一种对称加密算法,可以用于数据的加密和解密。Java中提供了KeyGenerator类来生成密钥,Cipher类来进行加密和解密。其基本使用方式如下:

import java.security.Key;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;

public class DESUtils {
    
    private static final String DES = "DES";
    
    /**
     * 生成随机密钥
     * @return DES密钥
     * @throws Exception
     */
    public static String generateDESKey() throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(DES);
        keyGenerator.init(56);
        Key key = keyGenerator.generateKey();
        return Base64.getEncoder().encodeToString(key.getEncoded());
    }
    
    /**
     * DES加密
     * @param content 待加密内容
     * @param key DES密钥
     * @return 加密结果
     * @throws Exception
     */
    public static String encryptDES(String content, String key) throws Exception {
        Key secretKey = new javax.crypto.spec.SecretKeySpec(Base64.getDecoder().decode(key), DES);
        Cipher cipher = Cipher.getInstance(DES);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] bytes = cipher.doFinal(content.getBytes());
        return Base64.getEncoder().encodeToString(bytes);
    }
    
    /**
     * DES解密
     * @param content 待解密内容
     * @param key DES密钥
     * @return 解密结果
     * @throws Exception
     */
    public static String decryptDES(String content, String key) throws Exception {
        Key secretKey = new javax.crypto.spec.SecretKeySpec(Base64.getDecoder().decode(key), DES);
        Cipher cipher = Cipher.getInstance(DES);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] byteContent = Base64.getDecoder().decode(content);
        byte[] bytes = cipher.doFinal(byteContent);
        return new String(bytes);
    }
}

以上是Java中MD5、RSA、AES、DES算法的简单介绍和实现方法,开发人员可以根据实际需要进行使用。此外,在实际应用中需要注意数据的安全性和加密算法的可靠性。