java实现的DES加密算法详解

作者:听着music睡 时间:2022-10-01 09:51:11 

本文实例讲述了java实现的DES加密算法。分享给大家供大家参考,具体如下:

一、DES加密算法介绍

1、要求密钥必须是8个字节,即64bit长度

2、因为密钥是byte[8] , 代表字符串也可以是非可见的字节,可以与Base64编码算法一起使用

3、加密、解密都需要通过字节数组作为数据和密钥进行处理

二、对称加密

DES加密算法属于对称加密。

即利用指定的密钥,按照密码的长度截取数据,分成数据块,和密钥进行复杂的移位、算数运算或者数据处理等操作,形成只有特定的密码才能够解开的数据。 加密与解密用的是同一个密钥

三、相关类

1、Cipher:

Java/Android要使用任何加密,都需要使用Cipher这个类

使用Cipher进行加密,解密处理,需要创建实例对象并初始化。采用工厂模式创建对象

Cipher cipher = Cipher.getInstance("算法名称");
cipher.init(加密/解密模式,Key秒);

2、Key:

Key类是Java加密系统所有密码的父类

3、SecretKeyFactory:

对于DES加密解密,使用SecretKeyFactory生成,生成时需指定DESKeySpec

四、加密代码步骤

1. 获取Cipher对象,设置加密算法


Cipher cipher = Cipher.getInstance("DES");

2、准备Key对象

2.1 DES加密算法使用DESKeySpec类,构造方法参数需要为8个字节的密码

创建DESKeySpec类对象

参数为密钥,8个字节


DESKeySpec keySpec = new DESKeySpec(new byte[1,2,3,4,5,6,7,8]);

2.2 转换成Key对象


SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("EDS");
SecretKey key = keyFactory.generateSecret(keySpec);

3.设置Cipher模式,加密/解密 ,参数一 :模式 ,参数二:Key对象,返回字节数组

Cipher.DECRYPT_MODE 解密
Cipher.ENCRYPT_MODE 加密


cipher.init(Cipher.ENCRYPT_MODE,key);

4.返回加密结果,参数为加密内容


bytep[] ret = cipher.doFinal(data);

因为对称加密加密与解密是相逆的。所以解密步骤和加密步骤一样,只是cipher.init()的模式不同,所以我们可以写一个工具类来进行DES加密算法的加密解密

DES加密算法工具类


/**
* DES加密算法
* @param mode   模式: 加密,解密
* @param data   需要加密的内容
* @param keyData 密钥 8个字节数组
* @return     将内容加密后的结果也是byte[]格式的
*/
public static byte[] des(int mode,byte[] data,byte[] keyData)
{
   byte[] ret = null;
   //加密的内容存在并且密钥存在且长度为8个字节
   if (data != null
       && data.length>0
       &&keyData!=null
       && keyData.length==8) {
     try {
       Cipher cipher = Cipher.getInstance("DES");
       DESKeySpec keySpec = new DESKeySpec(keyData);
       SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
       SecretKey key = keyFactory.generateSecret(keySpec);
       cipher.init(mode, key);
       ret = cipher.doFinal(data);
     } catch (NoSuchAlgorithmException e) {
       e.printStackTrace();
     } catch (NoSuchPaddingException e) {
       e.printStackTrace();
     } catch (IllegalBlockSizeException e) {
       e.printStackTrace();
     } catch (BadPaddingException e) {
       e.printStackTrace();
     } catch (InvalidKeySpecException e) {
       e.printStackTrace();
     } catch (InvalidKeyException e) {
       e.printStackTrace();
     }
   }
   return ret;
}
//DES 加密
public static byte[] desEncrypt(byte[] data,byte[] keyData){
   return des(Cipher.ENCRYPT_MODE,data,keyData);
}
//DES 解密
public static byte[] desDecrypt(byte[] data,byte[] keyData){
   return des(Cipher.DECRYPT_MODE,data,keyData);
}

五、示例

SythEncryptActivity.class:


package com.xqx.encrypsthow;
import android.app.Activity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import utils.EncryptUtil;
import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Arrays;
/**
* Created by Administrator on 2015/10/16.
*/
/**
* 对称加密
*/
public class SythEncryptActivity extends Activity {
 private EditText txtContent;
 private EditText txtPassword;
 private EditText txtResult;
 @Override
 public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.sythencrypylayout);
   txtContent = (EditText) findViewById(R.id.txt_content);
   txtPassword = (EditText) findViewById(R.id.txt_password);
   txtResult = (EditText) findViewById(R.id.txt_result);
 }
 /**
  * DES加密,要求密码必须8个字节,64bit长度 byte[8]
  * @param view
  */
 public void btnDESEncrypt(View view) {
   //获取需要加密的内容
   String content = txtContent.getText().toString();
   //获取密钥
   String password = txtPassword.getText().toString();
   //注意,加密,解密,秘钥都需要是字节数组
   byte[] keyData = password.getBytes();
   //需要加密的内容
   byte[] contentData = content.getBytes();
   if(keyData.length == 8) {
     byte[] encryptedData = EncryptUtil.des(Cipher.ENCRYPT_MODE, contentData, keyData);
     //获取加密后的数据(记住是byte[]类型的),用Base64编码 成可见的字符串形式
     String s = Base64.encodeToString(encryptedData, Base64.NO_WRAP);
     //显示加密后的内容
     txtResult.setText(s);
   }
 }
 /**
  * DES的解密
  * @param view
  */
 public void btnDESDecrypt(View view) {
   String encryptedStr = txtResult.getText().toString();
   if(encryptedStr.length()>0){
     String password = txtPassword.getText().toString();
     //因为在加密方法中,使用Base64对加密的内容进行编码,要解密的时候需要Base64的解码
     byte[] encryptedData = Base64.decode(encryptedStr, Base64.NO_WRAP);
     byte[] keyData = password.getBytes();
     //DES 要求 8个字节
     if(keyData.length == 8){
       //形成原始数据
       byte[] decryptedData = EncryptUtil.des(Cipher.DECRYPT_MODE, encryptedData, keyData);
       txtResult.setText(new String(decryptedData));
     }
   }
 }
}

layout:


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:orientation="vertical"
      android:layout_width="match_parent"
      android:layout_height="match_parent">
 <EditText
     android:id="@+id/txt_content"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:hint="请输入内容"
     />
 <EditText
     android:id="@+id/txt_password"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:hint="DES密钥"
     android:text="12345678"
     android:inputType="textVisiblePassword"
     />
 <EditText
     android:id="@+id/txt_result"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     />
 <Button
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text="DES加密"
     android:onClick="btnDESEncrypt"
     />
 <Button
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text="DES解密"
     android:onClick="btnDESDecrypt"
     />
</LinearLayout>

工具类参考 四:加密代码步骤

效果图:

java实现的DES加密算法详解

PS:关于加密解密感兴趣的朋友还可以参考本站在线工具:

MD5在线加密工具:
http://tools.jb51.net/password/CreateMD5Password

迅雷、快车、旋风URL加密/解密工具:
http://tools.jb51.net/password/urlrethunder

在线散列/哈希算法加密工具:
http://tools.jb51.net/password/hash_encrypt

在线MD5/hash/SHA-1/SHA-2/SHA-256/SHA-512/SHA-3/RIPEMD-160加密工具:
http://tools.jb51.net/password/hash_md5_sha

在线sha1/sha224/sha256/sha384/sha512加密工具:
http://tools.jb51.net/password/sha_encode

希望本文所述对大家java程序设计有所帮助。

标签:java,DES,加密算法
0
投稿

猜你喜欢

  • 基于MapReduce实现决策树算法

    2023-10-20 16:05:40
  • springboot2.0使用Hikari连接池的方法(替换druid)

    2023-04-12 00:54:33
  • java设计模式理解依赖于抽象不依赖具体的分析

    2023-09-13 01:41:45
  • Hutool Java工具类库_ExcelUtil的使用

    2022-09-08 07:30:28
  • 详解SpringMVC和MyBatis框架开发环境搭建和简单实用

    2022-03-11 13:54:51
  • 关于ConditionalOnMissingBean失效问题的追踪

    2021-08-19 17:42:04
  • Android TabHost如何实现顶部选项卡

    2023-04-13 01:08:14
  • SpringBoot整合JDBC、Druid数据源的示例代码

    2022-06-19 20:44:24
  • android 实现APP中改变头像图片的实例代码

    2021-11-02 20:39:58
  • C#实现网络小程序的步骤详解

    2023-08-17 18:16:37
  • java中JSONObject转换为HashMap(方法+main方法调用实例)

    2023-08-10 04:04:08
  • Android取消EditText自动获取默认焦点

    2023-09-09 00:14:13
  • java 单例模式和工厂模式实例详解

    2023-04-07 22:10:19
  • 在Spring Boot中实现HTTP缓存的方法

    2023-10-06 14:18:16
  • Java实现五子棋游戏

    2022-07-08 12:50:27
  • Android WebView如何判定网页加载的错误

    2023-09-22 14:33:20
  • C语言实现自定义扫雷游戏(递归版)

    2023-11-03 02:12:36
  • Jackson中json格式的字符串与对象的互相转换方式

    2022-01-29 03:31:07
  • android编程之ip2id程序实例

    2023-07-20 16:08:09
  • WPF实现半圆形导航菜单

    2023-06-09 07:02:56
  • asp之家 软件编程 m.aspxhome.com