Java实现的常见加密解密算法

Java是一款非常流行的编程语言,广泛应用于各种领域。在实际的应用中,数据的加密和解密是很常见的需求。Java提供了许多加密解密算法,本文将简单介绍其中几种常见的算法。

一、对称加密算法

对称加密算法又叫私钥加密算法,是将加密和解密使用相同的密钥。常见的对称加密算法有DES、3DES、AES等。

  1. DES算法

DES(Data Encryption Standard)是一种经典的对称加密算法,它的密钥长度为56位。在使用DES算法时,需要先生成密钥,然后使用密钥加密明文,得到密文;再使用密钥解密密文,得到明文。在Java中,可以使用JCE(Java Cryptography Extension)提供的DES加密解密功能。示例代码如下:

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;

public class DESUtil {
    private static final String ALGORITHM = "DES";

    public static String encrypt(String content, String key) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(), ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        byte[] byteContent = content.getBytes();
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] result = cipher.doFinal(byteContent);
        return parseByte2HexStr(result);
    }

    public static String decrypt(String content, String key) throws Exception {
        byte[] decryptFrom = parseHexStr2Byte(content);
        SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(), ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        byte[] result = cipher.doFinal(decryptFrom);
        return new String(result);
    }

    private static String parseByte2HexStr(byte[] buf) {
        StringBuilder sb = new StringBuilder();
        for (byte b : buf) {
            String hex = Integer.toHexString(b & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    private static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) {
            return null;
        }
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    public static void main(String[] args) throws Exception {
        String content = "Hello World!";
        String key = "12345678";
        String encrypt = encrypt(content, key);
        System.out.println("加密后:" + encrypt);
        String decrypt = decrypt(encrypt, key);
        System.out.println("解密后:" + decrypt);
    }
}
  1. 3DES算法

3DES(Triple DES)算法是在DES算法的基础上加强的一种加密算法,密钥长度为168位。3DES算法的加密解密过程类似于DES算法,可以使用Java提供的JCE库进行实现。示例代码如下:

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;

public class TripleDESUtil {
    private static final String ALGORITHM = "DESede";

    private static byte[] initKey() throws NoSuchAlgorithmException {
        KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM);
        kg.init(168); // 3DES的密钥长度为168位
        SecretKey secretKey = kg.generateKey();
        return secretKey.getEncoded();
    }

    public static String encrypt(String content, byte[] key) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(key, ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        byte[] byteContent = content.getBytes();
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] result = cipher.doFinal(byteContent);
        return parseByte2HexStr(result);
    }

    public static String decrypt(String content, byte[] key) throws Exception {
        byte[] decryptFrom = parseHexStr2Byte(content);
        SecretKeySpec skeySpec = new SecretKeySpec(key, ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        byte[] result = cipher.doFinal(decryptFrom);
        return new String(result);
    }

    private static String parseByte2HexStr(byte[] buf) {
        StringBuilder sb = new StringBuilder();
        for (byte b : buf) {
            String hex = Integer.toHexString(b & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    private static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) {
            return null;
        }
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    public static void main(String[] args) throws Exception {
        String content = "Hello World!";
        byte[] key = initKey();
        String encrypt = encrypt(content, key);
        System.out.println("加密后:" + encrypt);
        String decrypt = decrypt(encrypt, key);
        System.out.println("解密后:" + decrypt);
    }
}
  1. AES算法

AES(Advanced Encryption Standard)算法是一种高级加密标准,是目前最流行的对称加密算法之一。AES算法的密钥长度一般为128位、192位或256位。在Java中,也可以使用JCE库提供的AES加密解密功能。示例代码如下:

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;

public class AESUtil {
    private static final String ALGORITHM = "AES";

    private static byte[] initKey() throws NoSuchAlgorithmException {
        KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM);
        kg.init(128); // AES的密钥长度为128位、192位、256位
        SecretKey secretKey = kg.generateKey();
        return secretKey.getEncoded();
    }

    public static String encrypt(String content, byte[] key) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(key, ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        byte[] byteContent = content.getBytes();
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] result = cipher.doFinal(byteContent);
        return parseByte2HexStr(result);
    }

    public static String decrypt(String content, byte[] key) throws Exception {
        byte[] decryptFrom = parseHexStr2Byte(content);
        SecretKeySpec skeySpec = new SecretKeySpec(key, ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        byte[] result = cipher.doFinal(decryptFrom);
        return new String(result);
    }

    private static String parseByte2HexStr(byte[] buf) {
        StringBuilder sb = new StringBuilder();
        for (byte b : buf) {
            String hex = Integer.toHexString(b & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    private static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) {
            return null;
        }
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    public static void main(String[] args) throws Exception {
        String content = "Hello World!";
        byte[] key = initKey();
        String encrypt = encrypt(content, key);
        System.out.println("加密后:" + encrypt);
        String decrypt = decrypt(encrypt, key);
        System.out.println("解密后:" + decrypt);
    }
}

二、非对称加密算法

非对称加密算法又叫公钥加密算法,是加密和解密使用不同的密钥。常见的非对称加密算法有RSA算法。

  1. RSA算法

RSA算法是一种非对称加密算法,是一种基于大整数的数论加密算法。RSA算法的特点是公钥可以公开,密钥是私有的,因此安全性较高。在Java中,也可以使用JCE库提供的RSA加密解密功能。示例代码如下:

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

public class RSAUtil {
    private static final String ALGORITHM = "RSA";

    private static KeyPair getKeyPair(int keySize) throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM);
        keyPairGenerator.initialize(keySize);
        return keyPairGenerator.generateKeyPair();
    }

    public static String encrypt(String content, PublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] byteContent = content.getBytes();
        byte[] result = cipher.doFinal(byteContent);
        return parseByte2HexStr(result);
    }

    public static String decrypt(String content, PrivateKey privateKey) throws Exception {
        byte[] decryptFrom = parseHexStr2Byte(content);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] result = cipher.doFinal(decryptFrom);
        return new String(result);
    }

    private static String parseByte2HexStr(byte[] buf) {
        StringBuilder sb = new StringBuilder();
        for (byte b : buf) {
            String hex = Integer.toHexString(b & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    private static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) {
            return null;
        }
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    public static void main(String[] args) throws Exception {
        String content = "Hello World!";
        KeyPair keyPair = getKeyPair(1024);
        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();
        String encrypt = encrypt(content, publicKey);
        System.out.println("加密后:" + encrypt);
        String decrypt = decrypt(encrypt, privateKey);
        System.out.println("解密后:" + decrypt);
    }
}

以上就是几种常见的Java实现的加密解密算法。在实际的应用中,需要根据实际情况选择适合自己的加密解密算法,并根据具体的需求进行调整和优化。

以上就是Java实现的常见加密解密算法的详细内容,更多请关注www.sxiaw.com其它相关文章!