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

Java加密函数:如何进行数据加密和解密操作

发布时间:2023-06-18 20:43:15

Java提供了多种加密算法和相关API,可用于数据加密和解密操作。下面我们将介绍Java中常用的加密函数及其使用方法。

一、消息摘要算法

消息摘要算法是一种单向散列算法,可以将任意长度的消息摘要成定长的哈希值。在Java中常见的消息摘要算法有MD5和SHA。可以使用java.security.MessageDigest类进行消息摘要计算操作。

1、MD5加密

MD5算法摘要出的哈希值长度为16字节,128位,通常被表示为32个16进制数。下面是一个MD5摘要计算的示例代码:

public static String md5(String input) {
    MessageDigest md = null;
    byte[] md5Bytes = null;
    try {
        md = MessageDigest.getInstance("MD5");
        md5Bytes = md.digest(input.getBytes());
    } catch (Exception e) {
        e.printStackTrace();
    }
    StringBuffer hexValue = new StringBuffer();
    for (int i = 0; i < md5Bytes.length; i++) {
        int val = ((int) md5Bytes[i]) & 0xff;
        if (val < 16) {
            hexValue.append("0");
        }
        hexValue.append(Integer.toHexString(val));
    }
    return hexValue.toString();
}

2、SHA加密

SHA算法摘要出的哈希值长度可以为160位、224位和256位,可以使用SHA-1、SHA-224、SHA-256等。下面是一个SHA-256摘要计算的示例代码:

public static String sha256(String input) {
    MessageDigest md = null;
    byte[] sha256Bytes = null;
    try {
        md = MessageDigest.getInstance("SHA-256");
        sha256Bytes = md.digest(input.getBytes());
    } catch (Exception e) {
        e.printStackTrace();
    }
    StringBuffer hexValue = new StringBuffer();
    for (int i = 0; i < sha256Bytes.length; i++) {
        int val = ((int) sha256Bytes[i]) & 0xff;
        if (val < 16) {
            hexValue.append("0");
        }
        hexValue.append(Integer.toHexString(val));
    }
    return hexValue.toString();
}

二、对称加密算法

对称加密算法又称为共享密钥加密算法,加密和解密使用同一密钥。在Java中常见的对称加密算法有DES、AES和DESede等。可以使用javax.crypto.Cipher类进行对称加密和解密操作。

1、AES加密

AES算法使用一个128位、192位或256位的密钥对数据进行加密和解密。下面是一个AES加密和解密的示例代码:

public static byte[] aesEncrypt(byte[] input, String key) throws Exception {
    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
    secureRandom.setSeed(key.getBytes());
    kgen.init(128, secureRandom);
    SecretKey secretKey = kgen.generateKey();
    byte[] enCodeFormat = secretKey.getEncoded();
    SecretKeySpec keySpec = new SecretKeySpec(enCodeFormat, "AES");

    Cipher cipher = Cipher.getInstance("AES");// 创建密码器
    cipher.init(Cipher.ENCRYPT_MODE, keySpec);// 初始化
    byte[] result = cipher.doFinal(input);
    return result;
}

public static byte[] aesDecrypt(byte[] input, String key) throws Exception {
    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
    secureRandom.setSeed(key.getBytes());
    kgen.init(128, secureRandom);
    SecretKey secretKey = kgen.generateKey();
    byte[] enCodeFormat = secretKey.getEncoded();
    SecretKeySpec keySpec = new SecretKeySpec(enCodeFormat, "AES");

    Cipher cipher = Cipher.getInstance("AES");// 创建密码器
    cipher.init(Cipher.DECRYPT_MODE, keySpec);// 初始化
    byte[] result = cipher.doFinal(input);
    return result;
}

2、DES加密

DES算法使用一个56位的密钥对数据进行加密和解密,但在Java中DES算法的密钥长度只能是56位。由于DES加密已经不安全,一般不再使用。下面是一个DES加密和解密的示例代码:

public static byte[] desEncrypt(byte[] input, String key) throws Exception {
    KeyGenerator kgen = KeyGenerator.getInstance("DES");
    SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
    secureRandom.setSeed(key.getBytes());
    kgen.init(56, secureRandom);
    SecretKey secretKey = kgen.generateKey();

    Cipher cipher = Cipher.getInstance("DES");// 创建密码器
    cipher.init(Cipher.ENCRYPT_MODE, secretKey);// 初始化
    byte[] result = cipher.doFinal(input);
    return result;
}

public static byte[] desDecrypt(byte[] input, String key) throws Exception {
    KeyGenerator kgen = KeyGenerator.getInstance("DES");
    SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
    secureRandom.setSeed(key.getBytes());
    kgen.init(56, secureRandom);
    SecretKey secretKey = kgen.generateKey();

    Cipher cipher = Cipher.getInstance("DES");// 创建密码器
    cipher.init(Cipher.DECRYPT_MODE, secretKey);// 初始化
    byte[] result = cipher.doFinal(input);
    return result;
}

三、非对称加密算法

非对称加密算法又称为公开密钥加密算法,加密和解密使用不同的密钥。在Java中常见的非对称加密算法有RSA、DSA和ECC等。可以使用java.security.KeyPairGenerator和javax.crypto.Cipher类进行非对称加密和解密操作。

1、RSA加密

RSA算法使用一个公钥和一个私钥,公钥可以公开,私钥必须保密。下面是一个RSA加密和解密的示例代码:

public static byte[] rsaEncrypt(byte[] input, PublicKey publicKey) throws Exception {
    Cipher cipher = Cipher.getInstance("RSA");// 创建密码器
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);// 初始化
    byte[] result = cipher.doFinal(input);
    return result;
}

public static byte[] rsaDecrypt(byte[] input, PrivateKey privateKey) throws Exception {
    Cipher cipher = Cipher.getInstance("RSA");// 创建密码器
    cipher.init(Cipher.DECRYPT_MODE, privateKey);// 初始化
    byte[] result = cipher.doFinal(input);
    return result;
}

public static KeyPair generateKeyPair() throws Exception {
    KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
    keyPairGen.initialize(1024);
    KeyPair keyPair = keyPairGen.generateKeyPair();
    return keyPair;
}

2、ECC加密

ECC算法使用一个公钥和一个私钥,公钥可以公开,私钥必须保密。与RSA相比,ECC使用更短的密钥可以提供更高的安全性。下面是一个ECC加密和解密的示例代码:

public static byte[] eccEncrypt(byte[] input, PublicKey publicKey) throws Exception {
    Cipher cipher = Cipher.getInstance("ECIES");// 创建密码器
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);// 初始化
    byte[] result = cipher.doFinal(input);
    return result;
}

public static byte[] eccDecrypt(byte[] input, PrivateKey privateKey) throws Exception {
    Cipher cipher = Cipher.getInstance("ECIES");// 创建密码器
    cipher.init(Cipher.DECRYPT_MODE, privateKey);// 初始化
    byte[] result = cipher.doFinal(input);
    return result;
}

public static KeyPair generateKeyPair() throws Exception {
    KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("EC");
    ECGenParameterSpec ecSpec = new ECGenParameterSpec("secp256k1");//192位secp192k1
    SecureRandom random = new SecureRandom();
    keyPairGen.initialize(ecSpec, random);
    KeyPair keyPair = keyPairGen.generateKeyPair();
    return keyPair;
}

以上就是Java中常用的加密函数及其使用方法。在实际应用中,需要根据实际情况选择合适的加密算法和加密方式。