常用加密算法的Java实现

1.对称加密----AES和DES加密、解密

[url]http://www.cnblogs.com/lianghui66/archive/2013/03/07/2948494.html[/url]

2.常用加密算法的Java实现总结(二)——对称加密算法DES、3DES和AES

[url]http://www.blogjava.net/amigoxie/archive/2014/07/06/415503.html[/url]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java提供了许多对称加密算法实现,下面是一种常见的实现方式: ```java import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import java.util.Base64; public class SymmetricEncryption { public static void main(String[] args) throws Exception { String plainText = "Hello, world!"; String secretKey = "ThisIsASecretKey"; // Create the key SecretKey key = new SecretKeySpec(secretKey.getBytes(), "AES"); // Create the cipher Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key); // Encrypt the plaintext byte[] encryptedText = cipher.doFinal(plainText.getBytes()); String encryptedBase64 = Base64.getEncoder().encodeToString(encryptedText); System.out.println("Encrypted text: " + encryptedBase64); // Decrypt the encrypted text cipher.init(Cipher.DECRYPT_MODE, key); byte[] decryptedText = cipher.doFinal(Base64.getDecoder().decode(encryptedBase64)); System.out.println("Decrypted text: " + new String(decryptedText)); } } ``` 在上面的代码中,我们使用了AES算法进行加密和解密。首先,我们创建了一个SecretKey对象,该对象是由密钥字符串构造而成的。然后,我们创建了一个Cipher对象,该对象用于加密或解密数据。我们将加密模式设置为ENCRYPT_MODE,以便它知道我们要加密数据。我们使用doFinal方法对明文进行加密,并将结果转换为Base64编码的字符串。最后,我们使用相同的密钥和Cipher对象将加密后的文本解密,并打印出解密后的明文。 需要注意的是,这里我们使用了ECB模式和PKCS5Padding填充。这些是常见的模式和填充方式,但在实际应用中,可能需要根据具体需求选择不同的模式和填充方式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值