加密篇之三 - Base64

用jdk实现

BASE64Encoder encoder = new BASE64Encoder();
String encode = encoder.encode(src.getBytes());
System.out.println("encode:" + encode);

BASE64Decoder decoder = new BASE64Decoder();
System.out.println("decode:" + new String(decoder.decodeBuffer(encode)));

用Apache的common codes实现

byte[] encodeBytes = Base64.encodeBase64(src.getBytes());
System.out.println("common codes encode:" + new String(encodeBytes));

byte[] dencodeBytes = Base64.decodeBase64(encodeBytes);
System.out.println("common codes decode:" + new String(dencodeBytes));

用bouncy castle实现

byte[] encodeBytes = org.bouncycastle.util.encoders.Base64.encode(src.getBytes());
System.out.println("bouncy castle encode:" + new String(encodeBytes));

byte[] dencodeBytes = org.bouncycastle.util.encoders.Base64.decode(encodeBytes);
System.out.println("bouncy castle decode:" + new String(dencodeBytes));


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,这里是一个使用Java实现AES算法的示例代码: ```java import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.util.Base64; public class AESExample { private static final String KEY = "mySecretKey12345"; // 密钥,16个字符 public static void main(String[] args) throws Exception { String originalText = "Hello World!"; // 原始文本 // 加密 byte[] encryptedBytes = encrypt(originalText.getBytes(StandardCharsets.UTF_8)); String encryptedText = Base64.getEncoder().encodeToString(encryptedBytes); System.out.println("加密后:" + encryptedText); // 解密 byte[] decryptedBytes = decrypt(Base64.getDecoder().decode(encryptedText)); String decryptedText = new String(decryptedBytes, StandardCharsets.UTF_8); System.out.println("解密后:" + decryptedText); } private static byte[] encrypt(byte[] input) throws Exception { SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(StandardCharsets.UTF_8), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, keySpec); return cipher.doFinal(input); } private static byte[] decrypt(byte[] input) throws Exception { SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(StandardCharsets.UTF_8), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, keySpec); return cipher.doFinal(input); } } ``` 该示例代码使用AES算法对原始文本进行加密和解密,其中使用了ECB模式和PKCS5Padding填充方式。在加密过程中,首先将密钥转换为SecretKeySpec对象,然后使用Cipher类进行加密或解密操作。加密后的结果使用Base64进行编码以便于传输和存储。在解密过程中,将Base64编码的密文进行解码,然后使用同样的密钥和算法进行解密操作即可得到原始文本。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值