Java中加密方式之对称加密

大家好,我是程序员大猩猩。

大家都知道,作为一个程序员,在开发软件代码的时候,不可避免的会遇到数据的加密业务需求。比如说用户登录密码的加密,这是最简单的业务需求。还有一些为了更好的做到接口防护,接口信息也会要加密。

之前我写过一篇文章如下:

微服务巧用Aop,使用RequestBodyAdvice对请求参数加密,项目全局增强Api接口安全性

此文章是为了API的安全性,所以加密了请求块,而请求块是从前端下发到后端的,加密请求块到了后端之后,我们还需要将加密块进行解密才能够正确运行。

这种加密后还需要解密的方式我们叫做:对称加密。

对称加密使用相同的密钥进行加密和解密。加密速度快,适用于大量数据的加密。Java 中通过 javax.crypto 包提供对称加密支持,但是有些加密方式还需要导入其他组件包来实现,那么我们来说说对称加密有哪几种常见的加密方式,各种加密方式之间又有哪些不同。

a. AES (Advanced Encryption Standard)

AES是一种用于加密电子数据的对称加密算法,美国国家标准与技术研究院(NIST)在2001年发布了这项标准,用于替代DES加密标准。AES的区块长度固定为128位,密钥长度则可以是128、192或256位,因此也分别称为AES-128、AES-192和AES-256。

我们来写一段代码实例,来完成AES对称加密的理解。

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class AESExample {
    // AES密钥算法
    private static final String KEY_ALGORITHM = "AES";
    // 加密/解密算法/工作模式/填充方式
    private static final String CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
    /**
     * 生成密钥
     */
    public static String getSecretKey() throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM);
        keyGenerator.init(128); // 可以是128、192、256
        SecretKey secretKey = keyGenerator.generateKey();
        return Base64.getEncoder().encodeToString(secretKey.getEncoded());
    }
    /**
     * AES加密
     */
    public static String encrypt(String data, String key) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.getDecoder().decode(key), KEY_ALGORITHM);
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        byte[] encryptedBytes = cipher.doFinal(data.getBytes());
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }
    /**
     * AES解密
     */
    public static String decrypt(String encryptedData, String key) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.getDecoder().decode(key), KEY_ALGORITHM);
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
        return new String(decryptedBytes);
    }

    public static void main(String[] args) throws Exception {
        String data = "i love you";
        String secretKey = getSecretKey(); // 生成密钥
        String encryptedData = encrypt(data, secretKey); // 加密数据
        String decryptedData = decrypt(encryptedData, secretKey); // 解密数据
        System.out.println("原始数据: " + data);
        System.out.println("加密后的数据: " + encryptedData);
        System.out.println("解密后的数据: " + decryptedData);
    }
}

运行结果为:

原始数据: i love you
加密后的数据: 8YaBLUzY2uCPvejRMBQ6pQ==
解密后的数据: i love you

这里,我们一定要知道getSecretKey()生成密钥的的字符串后,不是每一次都需要生成的,我们生成一次后,然后妥善的保管好这个信息,以便使用。

b.DES (Data Encryption Standard)

DES使用56位的密钥对64位的数据块进行加密。由于56位的密钥长度相对较短,容易受到暴力破解攻击,因此DES现在被认为是不够安全的,在很多安全要求较高的场合已经被AES所取代。尽管如此,DES在以前的代码,或者一些老的项目上我们也会经常看到,这块我们要了解到。

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

public class DESExample {
    // DES密钥算法
    private static final String KEY_ALGORITHM = "DES";

    // 加密/解密算法/工作模式/填充方式
    private static final String CIPHER_ALGORITHM = "DES/ECB/PKCS5Padding";

    /**
     * 生成密钥
     */
    public static String getSecretKey() throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM);
        keyGenerator.init(56); // DES密钥长度固定为56位
        SecretKey secretKey = keyGenerator.generateKey();
        return Base64.getEncoder().encodeToString(secretKey.getEncoded());
    }

    /**
     * DES加密
     */
    public static String encrypt(String data, String key) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.getDecoder().decode(key), KEY_ALGORITHM);
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        byte[] encryptedBytes = cipher.doFinal(data.getBytes());
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    /**
     * DES解密
     */
    public static String decrypt(String encryptedData, String key) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.getDecoder().decode(key), KEY_ALGORITHM);
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
        return new String(decryptedBytes);
    }

    public static void main(String[] args) throws Exception {
        String data = "需要加密的内容";
        String secretKey = getSecretKey(); // 生成密钥
        String encryptedData = encrypt(data, secretKey); // 加密数据
        String decryptedData = decrypt(encryptedData, secretKey); // 解密数据

        System.out.println("原始数据: " + data);
        System.out.println("加密后的数据: " + encryptedData);
        System.out.println("解密后的数据: " + decryptedData);
    }
}

运行结果:

结果:
原始数据: i love you
加密后的数据: ndOpMUf3zHQUBV0Jw0xiyg==
解密后的数据: i love you

可以看到此代码示例与AES相仿,所以一些老项目和我们使用时,最好更改为AES方式加密。

c. 3DES (Triple Data Encryption Standard)

3DES我们也可以叫它Triple DES或TDES,它是一种使用三条56位的DES密钥对数据进行三次加密的块加密算法。3DES提供了对DES的向后兼容性,并且通过使用多个密钥,显著提高了加密强度。

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

public class TripleDESExample {
    // 3DES密钥算法
    private static final String KEY_ALGORITHM = "DESede";

    // 加密/解密算法/工作模式/填充方式
    private static final String CIPHER_ALGORITHM = "DESede/ECB/PKCS5Padding";

    /**
     * 生成密钥
     */
    public static String getSecretKey() throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM);
        keyGenerator.init(168); // 3DES密钥长度固定为168位
        SecretKey secretKey = keyGenerator.generateKey();
        return Base64.getEncoder().encodeToString(secretKey.getEncoded());
    }

    /**
     * 3DES加密
     */
    public static String encrypt(String data, String key) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.getDecoder().decode(key), KEY_ALGORITHM);
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        byte[] encryptedBytes = cipher.doFinal(data.getBytes());
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    /**
     * 3DES解密
     */
    public static String decrypt(String encryptedData, String key) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.getDecoder().decode(key), KEY_ALGORITHM);
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
        return new String(decryptedBytes);
    }

    public static void main(String[] args) throws Exception {
        String data = "hello world";
        String secretKey = getSecretKey(); // 生成密钥
        String encryptedData = encrypt(data, secretKey); // 加密数据
        String decryptedData = decrypt(encryptedData, secretKey); // 解密数据

        System.out.println("原始数据: " + data);
        System.out.println("加密后的数据: " + encryptedData);
        System.out.println("解密后的数据: " + decryptedData);
    }
}

运行结果:

原始数据: hello world
加密后的数据: qb8j6xefQzy5AdLPF3T3Xg==
解密后的数据: hello world

我们一定要知道,3DES虽然比DES更安全,但由于其处理速度较慢,且密钥长度仍然有限,它也被认为不是最理想的加密选择。在很多情况下,AES被推荐作为更现代、更安全的替代品。

d. RC4, RC5, RC6

RC4、RC5和RC6都是流加密或块加密算法,由Ron Rivest设计。它们在密码学中都有各自的特点和应用场景。1. RC4:RC4是一种流加密算法,以其速度快和实现简单而闻名。它使用变长密钥,从1到256位不等。RC4曾经被广泛应用于各种加密协议中,如WEP(无线等效加密)和SSL/TLS。但是,由于发现了多个安全漏洞,它的使用已经逐渐减少。在Java中,由于RC4算法的专利问题,它没有直接在标准库中提供。但是,我们可以使用第三方库来实现RC4加密和解密。2. RC5:RC5是一种块加密算法,提供了一种可变的块大小、密钥大小和加密轮数。它的设计目标是提供高速的加密和解密,同时保持高安全性。RC5的块大小可以是32、64或128位,密钥大小可以是0到2040位。在Java中,RC5也没有直接在标准库中提供。你需要使用第三方库来实现RC5加密和解密。3. RC6:RC6是一种基于RC5的块加密算法,它是为了参与AES(高级加密标准)的竞争而设计的。RC6提供了更大的块大小(128位)和密钥大小(最大256位),并且加密轮数也比RC5多。和RC4、RC5一样,RC6也没有在Java的标准库中提供。你需要使用第三方库来实现RC6加密和解密。由于这些算法的专利问题和安全性问题,那么我们可以用哪些库来实现RC的加密算法呢?比如说我们在波场区块链开发时就会用到的bouncycastle,该组件内就包含有RC5、RC6的实现。

<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcprov-jdk15on</artifactId>
    <version>1.68</version>
</dependency>

e. Blowfish

Blowfish是一种对称密钥块加密算法,由Bruce Schneier在1993年设计。

它是一种快速、紧凑的算法,可以用于加密数据块,其块大小为64位,密钥长度可变,最长可达448位。Blowfish算法因其简单性和灵活性而广受欢迎,尽管它现在可能不被认为是最高安全级别的加密算法,但在某些应用中仍然可以使用。

在Java中,Blowfish算法可以通过第三方库来实现,因为Java的标准加密库(JCE)没有内置对Blowfish的支持。

那么我们怎么实现它呢,我们可以使用以上RC5、RC6的bouncycastle就可以实现。如项目中已经导入了bouncycastle,我们来写一段代码示例来完成。

import org.bouncycastle.crypto.engines.BlowfishEngine;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class BlowfishExample {
    public static void main(String[] args) throws Exception {
        String data = "hello world";
        String key = "mysecretkey"; // 密钥长度应为8到448位
        // 加密
        byte[] encryptedData = encrypt(data, key);
        System.out.println("加密时的数据: " + data);
        System.out.println("加密后的数据: " + Base64.getEncoder().encodeToString(encryptedData));
        // 解密
        byte[] decryptedData = decrypt(encryptedData, key);
        System.out.println("解密后的数据: " + new String(decryptedData));
    }

    public static byte[] encrypt(String data, String key) throws Exception {
        BlowfishEngine engine = new BlowfishEngine();
        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(engine);
        KeyParameter keyParam = new KeyParameter(key.getBytes(StandardCharsets.UTF_8));
        cipher.init(true, keyParam);
        byte[] inputBytes = data.getBytes(StandardCharsets.UTF_8);
        byte[] outputBytes = new byte[cipher.getOutputSize(inputBytes.length)];
        int bytesProcessed1 = cipher.processBytes(inputBytes, 0, inputBytes.length, outputBytes, 0);
        int bytesProcessed2 = cipher.doFinal(outputBytes, bytesProcessed1);
        byte[] encryptedData = new byte[bytesProcessed1 + bytesProcessed2];
        System.arraycopy(outputBytes, 0, encryptedData, 0, encryptedData.length);
        return encryptedData;
    }

    public static byte[] decrypt(byte[] encryptedData, String key) throws Exception {
        BlowfishEngine engine = new BlowfishEngine();
        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(engine);
        KeyParameter keyParam = new KeyParameter(key.getBytes(StandardCharsets.UTF_8));
        cipher.init(false, keyParam);
        byte[] outputBytes = new byte[cipher.getOutputSize(encryptedData.length)];
        int bytesProcessed1 = cipher.processBytes(encryptedData, 0, encryptedData.length, outputBytes, 0);
        int bytesProcessed2 = cipher.doFinal(outputBytes, bytesProcessed1);
        byte[] decryptedData = new byte[bytesProcessed1 + bytesProcessed2];
        System.arraycopy(outputBytes, 0, decryptedData, 0, decryptedData.length);
        return decryptedData;
    }
}

运行结果:

加密时的数据: hello world
加密后的数据: x5VipecMs2EPf6k0Kjd7Tg==
解密后的数据: hello world

这里我们要记住一点信息,由于Blowfish算法可能不再被认为是最高安全级别的加密算法,我们还是应该考虑使用更现代的算法,如AES。

f. Twofish

如上,twofish的实现也可以使用bouncycastle组件来实现。

import org.bouncycastle.crypto.engines.TwofishEngine;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;
import java.util.Base64;

public class TwofishExample {
    public static void main(String[] args) throws Exception {
        String data = "hello world";
        String key = "mysecretkey"; // 密钥长度应为16、24或32字节

        // 加密
        byte[] encryptedData = encrypt(data, key);
        System.out.println("加密时的数据: " + data);
        System.out.println("加密后的数据: " + Base64.getEncoder().encodeToString(encryptedData));
        // 解密
        byte[] decryptedData = decrypt(encryptedData, key);
        System.out.println("解密后的数据: " + new String(decryptedData));
    }

    public static byte[] encrypt(String data, String key) throws Exception {
        TwofishEngine engine = new TwofishEngine();
        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(engine);
        KeyParameter keyParam = new KeyParameter(key.getBytes("UTF-8"));
        cipher.init(true, keyParam);
        byte[] inputBytes = data.getBytes("UTF-8");
        byte[] outputBytes = new byte[cipher.getOutputSize(inputBytes.length)];
        int bytesProcessed1 = cipher.processBytes(inputBytes, 0, inputBytes.length, outputBytes, 0);
        int bytesProcessed2 = cipher.doFinal(outputBytes, bytesProcessed1);
        byte[] encryptedData = new byte[bytesProcessed1 + bytesProcessed2];
        System.arraycopy(outputBytes, 0, encryptedData, 0, encryptedData.length);
        return encryptedData;
    }

    public static byte[] decrypt(byte[] encryptedData, String key) throws Exception {
        TwofishEngine engine = new TwofishEngine();
        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(engine);
        KeyParameter keyParam = new KeyParameter(key.getBytes("UTF-8"));
        cipher.init(false, keyParam);
        byte[] outputBytes = new byte[cipher.getOutputSize(encryptedData.length)];
        int bytesProcessed1 = cipher.processBytes(encryptedData, 0, encryptedData.length, outputBytes, 0);
        int bytesProcessed2 = cipher.doFinal(outputBytes, bytesProcessed1);
        byte[] decryptedData = new byte[bytesProcessed1 + bytesProcessed2];
        System.arraycopy(outputBytes, 0, decryptedData, 0, decryptedData.length);
        return decryptedData;
    }
}

运行结果:

加密时的数据: hello world
加密后的数据: j2yTgcTr6jTk7ga54drfGw==
解密后的数据: hello world

Twofish是一种对称密钥块加密算法,由Bruce Schneier和其他几位密码学家设计,作为AES(高级加密标准)竞赛的候选算法之一。

Twofish最终没有赢得AES竞赛,但它是其中一个最终入围的算法,并且被认为是非常安全的。

Twofish支持多种密钥长度,包括128位、192位和256位,并且使用128位的块大小。

  • 16
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

程序员大猩猩

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

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

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

打赏作者

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

抵扣说明:

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

余额充值