Androdi端DES字符串对称加密

本文介绍了一种在Android平台上实现DES加密解密的方法。通过创建DESUtil类封装了加密和解密的功能,并提供了具体的实现代码。该方法采用CBC模式和PKCS5填充方式,使用固定密钥进行加密解密操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

新建DESUtil.class文件,代码如下:

package cn.powerthink.djt.utils;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import android.annotation.SuppressLint;
import android.util.Base64;

public class DESUtil {

	// Android端DES对称加密解密 封装方法

	// 加密密码
	static String key = "pengthin";

	// 解密
	public static String Decryption(String message) throws Exception {
		byte[] bytesrc = Base64.decode(message.getBytes(), Base64.DEFAULT);
		Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
		DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
		IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
		cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
		byte[] retByte = cipher.doFinal(bytesrc);
		return new String(retByte).trim();
	}

	// 加密
	@SuppressLint("TrulyRandom")
	public static String Encryption(String message) throws Exception {
		// 替换字符:回车符 ——> "$@$"
		message = PublicClass.replace(message);
		Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
		DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
		IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
		cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
		byte[] encryptbyte = cipher.doFinal(message.getBytes());
		String a = new String(Base64.encode(encryptbyte, Base64.DEFAULT));
		// 替换字符:回车符 ——> ""
		String b = replace(a);
		return b;
	}

	// 替换字符:回车符 ——> "$@$"
	public static String replace(String str) {
		return str.replace("\n", "$@$");
	}

	// 替换字符:"$@$"——> 回车符
	public static String recover(String str) {
		return str.replace("$@$", "\n");
	}
}


备注:加密Encryption( ),解密Decryption( ) .使用时直接调用对应方法就Ok,调用方法时,把需要加密(或解密)的String字符串传入方法,方法执行完之后,返回加密(或解密)之后的String字符串。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值