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

Java中实现加密解密的相关函数

发布时间:2023-05-21 13:08:43

加密解密是编程中常见的一种操作。在Java中,加密解密的实现可以采用Java自带的加密解密算法,也可以采用第三方加密解密库。本文将介绍Java中实现加密解密的相关函数。

一、Java自带的加密解密算法

Java自带了多种加密解密算法,其中常用的有以下几种:

1. MD5加密

MD5是一种常见的加密方式,可以将任意长度的消息经过处理,生成一个128位的散列值。Java中使用MD5加密方式,可以使用java.security.MessageDigest类实现。具体操作如下:

import java.security.MessageDigest;

import java.security.NoSuchAlgorithmException;

 

public class MD5Utils {

 

    public static String getMD5(String input) {

        try {

            MessageDigest md = MessageDigest.getInstance("MD5");

            byte[] messageDigest = md.digest(input.getBytes());

            return convertByteArrayToHexString(messageDigest);

        } catch (NoSuchAlgorithmException e) {

            throw new RuntimeException(e);

        }

    }

 

    private static String convertByteArrayToHexString(byte[] arrayBytes) {

        StringBuffer sb = new StringBuffer();

        for (int i = 0; i < arrayBytes.length; i++) {

            sb.append(Integer.toString((arrayBytes[i] & 0xff) + 0x100, 16).substring(1));

        }

        return sb.toString();

    }

}

2. SHA加密

SHA是一种安全哈希算法,比MD5更复杂、更安全。Java中使用SHA加密方式,可以使用java.security.MessageDigest类实现。具体操作如下:

import java.security.MessageDigest;

import java.security.NoSuchAlgorithmException;

 

public class SHAUtils {

 

    public static String getSHA(String input) {

        try {

            MessageDigest md = MessageDigest.getInstance("SHA-256");

            byte[] messageDigest = md.digest(input.getBytes());

            return convertByteArrayToHexString(messageDigest);

        } catch (NoSuchAlgorithmException e) {

            throw new RuntimeException(e);

        }

    }

 

    private static String convertByteArrayToHexString(byte[] arrayBytes) {

        StringBuffer sb = new StringBuffer();

        for (int i = 0; i < arrayBytes.length; i++) {

            sb.append(Integer.toString((arrayBytes[i] & 0xff) + 0x100, 16).substring(1));

        }

        return sb.toString();

    }

}

3. DES加密

DES是一种对称密钥加密算法,加解密使用同一密钥。在Java中,DES加密方式可以使用javax.crypto.Cipher类实现。具体操作如下:

import javax.crypto.Cipher;

import javax.crypto.spec.SecretKeySpec;

 

public class DESUtils {

 

    public static String encryptDES(String input, String key) throws Exception {

        SecretKeySpec keySpec = new SecretKeySpec(key.getBytes("UTF-8"), "DES");

        Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");

        cipher.init(Cipher.ENCRYPT_MODE, keySpec);

        byte[] encryptedBytes = cipher.doFinal(input.getBytes("UTF-8"));

        return new String(encryptedBytes, "UTF-8");

    }

 

    public static String decryptDES(String input, String key) throws Exception {

        SecretKeySpec keySpec = new SecretKeySpec(key.getBytes("UTF-8"), "DES");

        Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");

        cipher.init(Cipher.DECRYPT_MODE, keySpec);

        byte[] decryptedBytes = cipher.doFinal(input.getBytes("UTF-8"));

        return new String(decryptedBytes, "UTF-8");

    }

}

以上就是Java自带的加密解密算法的实现方式。

二、第三方加密解密库

除了Java自带的加密解密算法,还可以使用第三方的加密解密库,比如Bouncy Castle。Bouncy Castle提供了多种加密解密算法,可以满足不同的需求。以下是使用Bouncy Castle实现加密解密的示例代码:

1. RSA加密解密

RSA是一种非对称加密算法,需要生成公钥和私钥来使用。在Java中,可以使用Bouncy Castle库实现RSA加密解密。具体操作如下:

import java.security.KeyPair;

import java.security.KeyPairGenerator;

import java.security.NoSuchAlgorithmException;

import java.security.SecureRandom;

 

import org.bouncycastle.crypto.AsymmetricBlockCipher;

import org.bouncycastle.crypto.CipherParameters;

import org.bouncycastle.crypto.generators.RSAKeyPairGenerator;

import org.bouncycastle.crypto.params.AsymmetricKeyParameter;

import org.bouncycastle.crypto.params.KeyGenerationParameters;

import org.bouncycastle.crypto.params.RSAKeyGenerationParameters;

import org.bouncycastle.crypto.params.RSAKeyParameters;

import org.bouncycastle.crypto.util.PrivateKeyFactory;

import org.bouncycastle.crypto.util.PublicKeyFactory;

import org.bouncycastle.crypto.util.SubjectPublicKeyInfoFactory;

 

public class RSAUtils {

 

    public static KeyPair generateRSAKeyPair(int keyLength) throws NoSuchAlgorithmException {

        RSAKeyPairGenerator generator = new RSAKeyPairGenerator();

        KeyGenerationParameters generationParameters = new RSAKeyGenerationParameters(

                new SecureRandom(), keyLength, 80);

        generator.init(generationParameters);

        return generator.generateKeyPair();

    }

 

    public static byte[] encryptRSA(byte[] input, RSAKeyParameters key) throws Exception {

        AsymmetricBlockCipher cipher = new org.bouncycastle.crypto.engines.RSAEngine();

        cipher.init(true, key);

        return cipher.processBlock(input, 0, input.length);

    }

 

    public static byte[] decryptRSA(byte[] input, RSAKeyParameters key) throws Exception {

        AsymmetricBlockCipher cipher = new org.bouncycastle.crypto.engines.RSAEngine();

        cipher.init(false, key);

        return cipher.processBlock(input, 0, input.length);

    }

 

    public static RSAKeyParameters getPublicKey(String base64PublicKey) throws Exception {

        return (RSAKeyParameters) PublicKeyFactory.createKey(

                SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(

                        org.bouncycastle.asn1.pkcs.RSAPublicKey.getInstance(

                                org.bouncycastle.util.encoders.Base64.decode(base64PublicKey))));

    }

 

    public static RSAKeyParameters getPrivateKey(String base64PrivateKey) throws Exception {

        return (RSAKeyParameters) PrivateKeyFactory.createKey(

                org.bouncycastle.asn1.pkcs.RSAPrivateKey.getInstance(

                        org.bouncycastle.util.encoders.Base64.decode(base64PrivateKey)));

    }

}

2. AES加密解密

AES是一种对称加密算法,可以使用Bouncy Castle库实现AES加密解密。具体操作如下:

import java.security.SecureRandom;

 

import javax.crypto.Cipher;

import javax.crypto.KeyGenerator;

import javax.crypto.SecretKey;

 

import org.bouncycastle.crypto.BufferedBlockCipher;

import org.bouncycastle.crypto.CipherParameters;

import org.bouncycastle.crypto.engines.AESEngine;

import org.bouncycastle.crypto.generators.PKCS5S2ParametersGenerator;

import org.bouncycastle.crypto.params.KeyParameter;

import org.bouncycastle.crypto.params.ParametersWithSalt;

 

public class AESUtils {

 

    public static byte[] generateAESKey(int keyLength) throws Exception {

        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");

        keyGenerator.init(keyLength, new SecureRandom());

        SecretKey key = keyGenerator.generateKey();

        return key.getEncoded();

    }

 

    public static byte[] encryptAES(byte[] input, byte[] key) throws Exception {

        byte[] salt = new byte[8];

        SecureRandom random = new SecureRandom();

        random.nextBytes(salt);

 

        PKCS5S2ParametersGenerator generator = new PKCS5S2ParametersGenerator(new AESEngine());

        generator.init(key, salt, 1000);

        CipherParameters cipherParameters = new ParametersWithSalt(new KeyParameter(key), salt, 1000);

 

        BufferedBlockCipher cipher = new BufferedBlockCipher(new AESEngine());

        cipher.init(true, cipherParameters);

 

        byte[] outputBuffer = new byte[cipher.getOutputSize(input.length)];

        int outputLen = cipher.processBytes(input, 0, input.length, outputBuffer, 0);

        outputLen += cipher.doFinal(outputBuffer, outputLen);

 

        byte[] encryptedData = new byte[outputLen + 8];

        System.arraycopy(salt, 0, encryptedData, 0, 8);

        System.arraycopy(outputBuffer, 0, encryptedData, 8, outputLen);

 

        return encryptedData;

    }

 

    public static byte[] decryptAES(byte[] input, byte[] key) throws Exception {

        byte[] salt = new byte[8];

        System.arraycopy(input, 0, salt, 0, 8);

 

        PKCS5S2ParametersGenerator generator = new PKCS5S2ParametersGenerator(new AESEngine());

        generator.init(key, salt, 1000);

        CipherParameters cipherParameters = new ParametersWithSalt(new KeyParameter(key), salt,