android des 加密解密

本文介绍了一种使用DES算法进行数据加密和解密的方法。包括了加密和解密的两个主要函数,以及如何生成用于DES算法的密钥。

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

	/** 加密 */
	public byte[] enDES(byte[] datasource, String password) {
		byte[] data = null;
		try {
			Log.e("Haj", "data:"+datasource.length+" password:" + password.length());
			SecretKeySpec key = new SecretKeySpec(getKey(password), "DES");
			Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding");  
			cipher.init(Cipher.ENCRYPT_MODE, key); 
			data = cipher.doFinal(datasource);
		} catch (Throwable e) {
			e.printStackTrace();
		}
		return data;
	}

	/** 解密 */
	public byte[] deDES(byte[] src, String password){
		byte[] data = null;
		try {
			SecretKeySpec key = new SecretKeySpec(getKey(password), "DES");
			Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding");  
			cipher.init(Cipher.DECRYPT_MODE, key); 
			data = cipher.doFinal(src);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		
		return data;
	}
	
	/** 
     * 自定义一个key 
     * @param string  
     */  
    public static byte[] getKey(String keyRule) {  
        Key key = null;  
        byte[] keyByte = keyRule.getBytes();  
        // 创建一个空的八位数组,默认情况下为0  
        byte[] byteTemp = new byte[8];  
        // 将用户指定的规则转换成八位数组  
        for (int i = 0; i < byteTemp.length && i < keyByte.length; i++) {  
            byteTemp[i] = keyByte[i];  
        }  
        key = new SecretKeySpec(byteTemp, "DES/ECB/NoPadding");  
        return key.getEncoded();  
    } 


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值