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

如何编写Java函数进行加密和解密的功能

发布时间:2023-06-02 17:59:42

在Java中,加密和解密功能可以使用Java Cryptography Extension (JCE)来完成。JCE提供了很多加密算法和解密算法,包括常用的对称加密算法和非对称加密算法。

一、对称加密

对称加密算法是指使用同一个密钥进行加密和解密的算法。常见的对称加密算法有DES、3DES、AES等。

1. 加密

对称加密的加密过程如下:

1)生成密钥

用KeyGenerator.getInstance(“算法”)方法生成对称密钥。

2)加密数据

用Cipher.getInstance(“算法/模式/填充方式”)方法获取Cipher对象,再用init(Cipher.ENCRYPT_MODE, key)方法初始化Cipher对象,使用doFinal(plaintext)方法进行加密。

代码:

public static byte[] encrypt(String algorithm, byte[] plaintext, byte[] key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {

    Key secretKey = new SecretKeySpec(key, algorithm);

    Cipher cipher = Cipher.getInstance(algorithm);

    cipher.init(Cipher.ENCRYPT_MODE, secretKey);

    return cipher.doFinal(plaintext);

}

其中,algorithm是算法名称;plaintext是明文数据;key是密钥。

2. 解密

对称加密的解密过程如下:

1)生成密钥

用SecretKeySpec(key, algorithm)方法生成对称密钥。

2)解密数据

用Cipher.getInstance(“算法/模式/填充方式”)方法获取Cipher对象,再用init(Cipher.DECRYPT_MODE, key)方法初始化Cipher对象,使用doFinal(ciphertext)方法进行解密。

代码:

public static byte[] decrypt(String algorithm, byte[] ciphertext, byte[] key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {

    Key secretKey = new SecretKeySpec(key, algorithm);

    Cipher cipher = Cipher.getInstance(algorithm);

    cipher.init(Cipher.DECRYPT_MODE, secretKey);

    return cipher.doFinal(ciphertext);

}

其中,algorithm是算法名称;ciphertext是密文数据;key是密钥。

二、非对称加密

非对称加密算法是指使用公钥和私钥进行加密和解密的算法,常见的非对称加密算法有RSA等。

1. 加密

非对称加密的加密过程如下:

1)生成密钥对

用KeyPairGenerator.getInstance(“算法”)方法生成密钥对,其中公钥和私钥是一对。

2)加密数据

用Cipher.getInstance(“算法/模式/填充方式”)方法获取Cipher对象,再用init(Cipher.ENCRYPT_MODE, publicKey)方法初始化Cipher对象,使用doFinal(plaintext)方法进行加密。

代码:

public static byte[] encrypt(String algorithm, byte[] plaintext, PublicKey publicKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {

    Cipher cipher = Cipher.getInstance(algorithm);

    cipher.init(Cipher.ENCRYPT_MODE, publicKey);

    return cipher.doFinal(plaintext);

}

其中,algorithm是算法名称;plaintext是明文数据;publicKey是公钥。

2. 解密

非对称加密的解密过程如下:

1)获取私钥

用getKeyPair().getPrivate()方法获取私钥。

2)解密数据

用Cipher.getInstance(“算法/模式/填充方式”)方法获取Cipher对象,再用init(Cipher.DECRYPT_MODE, privateKey)方法初始化Cipher对象,使用doFinal(ciphertext)方法进行解密。

代码:

public static byte[] decrypt(String algorithm, byte[] ciphertext, PrivateKey privateKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {

    Cipher cipher = Cipher.getInstance(algorithm);

    cipher.init(Cipher.DECRYPT_MODE, privateKey);

    return cipher.doFinal(ciphertext);

}

其中,algorithm是算法名称;ciphertext是密文数据;privateKey是私钥。

三、总结

以上就是Java中实现加密和解密功能的方法,其中对称加密算法适合在本地存储数据时使用,而非对称加密算法适合在网络传输数据时使用。在实际开发中,应根据具体需求和场景选择合适的加密算法。