源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

java实现的DES加密算法详解

  • 时间:2022-03-09 21:32 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:java实现的DES加密算法详解
本文实例讲述了java实现的DES加密算法。分享给大家供大家参考,具体如下: [b]一、DES加密算法介绍[/b] 1、要求密钥必须是8个字节,即64bit长度 2、因为密钥是byte[8] , 代表字符串也可以是非可见的字节,可以与Base64编码算法一起使用 3、加密、解密都需要通过字节数组作为数据和密钥进行处理 [b]二、对称加密[/b] DES加密算法属于对称加密。 即利用指定的密钥,按照密码的长度截取数据,分成数据块,和密钥进行复杂的移位、算数运算或者数据处理等操作,形成只有特定的密码才能够解开的数据。 加密与解密用的是同一个密钥 [b]三、相关类[/b] [b]1、Cipher:[/b] Java/Android要使用任何加密,都需要使用Cipher这个类 使用Cipher进行加密,解密处理,需要创建实例对象并初始化。采用工厂模式创建对象 Cipher cipher = Cipher.getInstance("算法名称"); cipher.init(加密/解密模式,Key秒); [b]2、Key:[/b] Key类是Java加密系统所有密码的父类 [b]3、SecretKeyFactory:[/b] 对于DES加密解密,使用SecretKeyFactory生成,生成时需指定DESKeySpec [b]四、加密代码步骤[/b] [b]1. 获取Cipher对象,设置加密算法[/b]
Cipher cipher = Cipher.getInstance("DES");

[b]2、准备Key对象[/b] 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);

[b]3.设置Cipher模式,加密/解密 ,参数一 :模式 ,参数二:Key对象,返回字节数组[/b] Cipher.DECRYPT_MODE 解密 Cipher.ENCRYPT_MODE 加密
cipher.init(Cipher.ENCRYPT_MODE,key);

[b]4.返回加密结果,参数为加密内容[/b]
bytep[] ret = cipher.doFinal(data);

因为对称加密加密与解密是相逆的。所以解密步骤和加密步骤一样,只是cipher.init()的模式不同,所以我们可以写一个工具类来进行DES加密算法的加密解密 [b]DES加密算法工具类[/b]
/**
* 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);
}

[b]五、示例[/b] 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>

工具类参考 四:加密代码步骤 效果图: [img]http://files.jb51.net/file_images/article/201706/2017626101607589.gif?201752610171[/img] [b]PS:关于加密解密感兴趣的朋友还可以参考本站在线工具:[/b] [b]MD5在线加密工具: [/b][url=http://tools.jb51.net/password/CreateMD5Password]http://tools.jb51.net/password/CreateMD5Password[/url] [b]迅雷、快车、旋风URL加密/解密工具: [/b][url=http://tools.jb51.net/password/urlrethunder]http://tools.jb51.net/password/urlrethunder[/url] [b]在线散列/哈希算法加密工具: [/b][url=http://tools.jb51.net/password/hash_encrypt]http://tools.jb51.net/password/hash_encrypt[/url] [b]在线MD5/hash/SHA-1/SHA-2/SHA-256/SHA-512/SHA-3/RIPEMD-160加密工具: [/b][url=http://tools.jb51.net/password/hash_md5_sha]http://tools.jb51.net/password/hash_md5_sha[/url] [b]在线sha1/sha224/sha256/sha384/sha512加密工具: [/b][url=http://tools.jb51.net/password/sha_encode]http://tools.jb51.net/password/sha_encode[/url] 更多关于java相关内容感兴趣的读者可查看本站专题:《[url=http://www.1sucai.cn/Special/949.htm]Java数学运算技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/632.htm]Java数据结构与算法教程[/url]》、《[url=http://www.1sucai.cn/Special/947.htm]Java字符与字符串操作技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/830.htm]Java操作DOM节点技巧总结[/url]》和《[url=http://www.1sucai.cn/Special/682.htm]Java缓存操作技巧汇总[/url]》 希望本文所述对大家java程序设计有所帮助。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部