3DES加密算法的Android-Java客户端与MVC-C#服务端的加解密问题

对于3DES等其他加密算法的异构平台交互,比如Java和C#的加解密提供者来说,其很多默认选项是不一样的。所以在使用过程中,要想在异构系统中能够正确的交互,必须正确设置provider的选项。

Java客户端加密的字符串是无法被正确解密的,在git上改动如下:


其访问代码如下:

package com.lerdian.api;

import com.lerdian.beans.RestApiResult;
import com.lerdian.gson.Gson;
import com.lerdian.util.L;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;

/**
 * This class will return string instance directly instead of template class
 * when visiting rest api.
 *
 * Created by Abel5 on 1/30/2015.
 */
public class RestApiStr extends RestApiBase<String> {
    public RestApiStr(String methodName) {
        super(String.class, methodName);
    }

    @Override
    protected RestApiResult<String> doInBackground(String... params) {
        HttpClient client = new DefaultHttpClient();
        HttpRequestBase req = null;
        try {
            if (HttpGet.METHOD_NAME.equals(methodName)) {
                req = new HttpGet(params[1]);
            } else if (HttpPost.METHOD_NAME.equals(methodName)) {
                // embed timestamp
                String json = embedTimestamp(params[0]);
//                L.d(json);
                String secret = EncryptUtils.encrypt3DES(json, "9833696A", "3DFC4EEA", "9FCF71E5");
                json = "{'s':'" + secret + "'}";
//                L.d(json);

                HttpEntity body = new StringEntity(json, HTTP.UTF_8);
                HttpPost post = new HttpPost(params[1]);
                post.setHeader("Content-Type", "application/json");
                post.setEntity(body);
                req = post;
            }

            L.i(req.getURI().toString());
            HttpResponse response = client.execute(req);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                String str = readToEnd(entity.getContent());
                L.i("GOT: " + str);
                return new RestApiResult<>(str);
            } else {
                String str = readToEnd(response.getEntity().getContent());
                return new RestApiResult<>(str, HTTP_ERROR + response.getStatusLine(), null);
            }
        } catch (Exception ex) {
            return new RestApiResult<>(TASK_EXCEPTION + ex.getLocalizedMessage(), ex);
        }
    }
}

对于C#来说,解密过程如下:

using ApiTool.Common;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace ApiTool
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void btnEncrypt_Click(object sender, RoutedEventArgs e)
        {
            string plain = editPlain.Text.Trim();
            if (plain.Length < 1)
            {
                plain = "{'ts':'" + DateTime.Now.ToString("o") + "'}";
            }
            else if (plain.IndexOf("'ts':") < 1)
            {
                plain = Helper.EmbedTimestamp(plain);
            }

            try
            {
                string secret = Helper.DES3Encrypt(plain, "9833696A", "3DFC4EEA", "9FCF71E5");
                editSecret.Text = JsonConvert.SerializeObject(new { s = secret });

                // copy to clipboard.
                Clipboard.SetText(editSecret.Text);
                txtStatus.Text = "Copied to clipboard: " + DateTime.Now.ToString("o");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + " - " + ex.StackTrace);
            }
        }

        private void btnDecrypt_Click(object sender, RoutedEventArgs e)
        {
            string secret = editSecret.Text.Trim();
            if (secret.Length < 1)
            {
                editPlain.Text = "";
                return;
            }

            try
            {
                dynamic so = JsonConvert.DeserializeObject(secret);
                if (so.s == null)
                {
                    editPlain.Text = "Bad Secret Text";
                    return;
                }

                string plain = Helper.DES3Decrypt((string)so.s, "9833696A", "3DFC4EEA", "9FCF71E5");
                editPlain.Text = plain;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + " - " + ex.StackTrace);
            }
        }
    }
}

Java的工具类完整代码如下:


package com.lerdian.api;

/**
 * Created by abel on 4/13/2015.
 */
import android.util.Base64;

import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class EncryptUtils {
    /// <summary>
    /// 3des解码
    /// </summary>
    /// <param name="value">待解密字符串</param>
    /// <param name="key">原始密钥字符串</param>
    /// <returns></returns>
    public static String decrypt3DES(String src, String key1, String key2, String key3) throws Exception {
        src = decryptMode(src, key1);
        src = decryptMode(src, key2);
        src = decryptMode(src, key3);
        return src;
    }

    /// <summary>
    /// 3des加密
    /// </summary>
    /// <param name="value">待加密字符串</param>
    /// <param name="strKey">原始密钥字符串</param>
    /// <returns></returns>
    public static String encrypt3DES(String src, String key1, String key2, String key3) throws Exception {
        src = encryptMode(src, key3);
        src = encryptMode(src, key2);
        src = encryptMode(src, key1);
        return src;
    }

    private static final String Algorithm = "DES/CBC/PKCS7Padding"; //定义 加密算法,可用 DES,DESede,Blowfish

    //keybyte为加密密钥,长度为24字节
    //src为被加密的数据缓冲区(源)
    public static String encryptMode(String src, String key) {
        try {
            //生成密钥
            SecretKey deskey = new SecretKeySpec(key.getBytes(), Algorithm); //加密
            Cipher c1 = Cipher.getInstance(Algorithm);
            byte[] m_btIV = { 0x78, (byte) 0x90, (byte) 0xAB, 0x12, 0x34, 0x56, (byte) 0xCD, (byte) 0xEF };
            IvParameterSpec iv = new IvParameterSpec(m_btIV);
            c1.init(Cipher.ENCRYPT_MODE, deskey, iv);

            return Base64.encodeToString(c1.doFinal(src.getBytes()), Base64.NO_WRAP);
        } catch (java.security.NoSuchAlgorithmException e1) {
            e1.printStackTrace();
        } catch (javax.crypto.NoSuchPaddingException e2) {
            e2.printStackTrace();
        } catch (java.lang.Exception e3) {
            e3.printStackTrace();
        }
        return null;
    }

    //keybyte为加密密钥,长度为24字节
    //src为加密后的缓冲区
    public static String decryptMode(String src, String key) {
        try { //生成密钥
            SecretKey deskey = new SecretKeySpec(key.getBytes(), Algorithm);
            //解密
            Cipher c1 = Cipher.getInstance(Algorithm);
            byte[] m_btIV = { 0x78, (byte) 0x90, (byte) 0xAB, 0x12, 0x34, 0x56, (byte) 0xCD, (byte) 0xEF };
            IvParameterSpec iv = new IvParameterSpec(m_btIV);
            c1.init(Cipher.DECRYPT_MODE, deskey, iv);

            byte[] buf = Base64.decode(src.getBytes(), Base64.NO_WRAP);
            return new String(c1.doFinal(buf));
        } catch (java.security.NoSuchAlgorithmException e1) {
            e1.printStackTrace();
        } catch (javax.crypto.NoSuchPaddingException e2) {
            e2.printStackTrace();
        } catch (java.lang.Exception e3) {
            e3.printStackTrace();
        }
        return null;
    }
}


C#的工具类完整代码如下:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace ApiTool.Common
{
    public class Helper
    {
        public static string EmbedTimestamp(string json)
        {
            json = json.Trim();
            return json.Substring(0, json.Length - 1) + ",'ts':'" + DateTime.Now.ToString("o") + "'}";
        }

        /// <summary>
        /// MD5 加密静态方法
        /// </summary>
        /// <param name="EncryptString">待加密的明文</param>
        /// <returns>加密后的密文</returns>
        public static string MD5Encrypt(string EncryptString)
        {
            if (string.IsNullOrEmpty(EncryptString))
            {
                throw (new Exception("明文不得为空!"));
            }

            MD5 m_ClassMD5 = new MD5CryptoServiceProvider();
            string m_strEncrypt = "";
            try
            {
                m_strEncrypt = BitConverter.ToString(m_ClassMD5.ComputeHash(Encoding.Default.GetBytes(EncryptString))).Replace("-", "");

            }
            catch (ArgumentException ex)
            {
                throw ex;
            }
            catch (CryptographicException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                m_ClassMD5.Clear();
            }
            return m_strEncrypt;
        }

        /// <summary>
        /// DES 加密(数据加密标准,速度较快,适用于加密大量数据的场合)
        /// </summary>
        /// <param name="EncryptString">待加密的明文</param>
        /// <param name="EncryptKey">加密的密钥</param>
        /// <returns>加密后的密文</returns>
        public static string DESEncrypt(string EncryptString, string EncryptKey)
        {
            if (string.IsNullOrEmpty(EncryptString))
            {
                throw (new Exception("明文不得为空!"));
            }
            if (string.IsNullOrEmpty(EncryptKey))
            {
                throw (new Exception("密钥不得为空!"));
            }
            if (EncryptKey.Length != 8)
            {
                throw new Exception("密钥必须为8位");
            }
            byte[] m_btIV = { 0x78, 0x90, 0xAB, 0x12, 0x34, 0x56, 0xCD, 0xEF };
            string m_strEncrypt = "";
            DESCryptoServiceProvider m_DESProvider = new DESCryptoServiceProvider();

            try
            {
                byte[] m_btEncryptString = Encoding.Default.GetBytes(EncryptString);
                MemoryStream m_stream = new MemoryStream();
                CryptoStream m_cstream = new CryptoStream(m_stream, m_DESProvider.CreateEncryptor(Encoding.Default.GetBytes(EncryptKey), m_btIV), CryptoStreamMode.Write);
                m_cstream.Write(m_btEncryptString, 0, m_btEncryptString.Length);
                m_cstream.FlushFinalBlock();
                m_strEncrypt = Convert.ToBase64String(m_stream.ToArray());
                m_stream.Close();
                m_stream.Dispose();
                m_cstream.Close();
                m_cstream.Dispose();
            }
            catch (IOException ex)
            {
                throw ex;
            }
            catch (ArgumentException ex)
            {
                throw ex;
            }
            catch (CryptographicException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                m_DESProvider.Clear();
            }

            return m_strEncrypt;
        }


        /// <summary>
        /// DES 解密(数据加密标准,速度较快,适用于加密大量数据的场合)
        /// </summary>
        /// <param name="DecryptString">待解密的密文</param>
        /// <param name="DecryptKey">解密的密钥</param>
        /// <returns>解密后的明文</returns>
        public static string DESDecrypt(string DecryptString, string DecryptKey)
        {
            if (string.IsNullOrEmpty(DecryptString))
            {
                throw (new Exception("密文不得为空!"));
            }
            if (string.IsNullOrEmpty(DecryptKey))
            {
                throw (new Exception("密钥不得为空!"));
            }
            if (DecryptKey.Length != 8)
            {
                throw new Exception("密钥必须为8位");
            }
            byte[] m_btIV = { 0x78, 0x90, 0xAB, 0x12, 0x34, 0x56, 0xCD, 0xEF };
            string m_strDecrypt = "";

            DESCryptoServiceProvider m_DESProvider = new DESCryptoServiceProvider();

            try
            {
                byte[] m_btDecryptString = Convert.FromBase64String(DecryptString);
                MemoryStream m_stream = new MemoryStream();
                CryptoStream m_cstream = new CryptoStream(m_stream, m_DESProvider.CreateDecryptor(Encoding.Default.GetBytes(DecryptKey), m_btIV), CryptoStreamMode.Write);
                m_cstream.Write(m_btDecryptString, 0, m_btDecryptString.Length);
                m_cstream.FlushFinalBlock();
                m_strDecrypt = Encoding.Default.GetString(m_stream.ToArray());
                m_stream.Close();
                m_stream.Dispose();
                m_cstream.Close();
                m_cstream.Dispose();
            }
            catch (IOException ex)
            {
                throw ex;
            }
            catch (ArgumentException ex)
            {
                throw ex;
            }
            catch (CryptographicException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                m_DESProvider.Clear();
            }

            return m_strDecrypt;
        }

        /* /// <summary>
          /// DES 解密(数据加密标准,速度较快,适用于加密大量数据的场合)
          /// </summary>
          /// <param name="DecryptString">待解密的密文</param>
          /// <param name="DecryptKey">解密的密钥</param>
          /// <returns>returns</returns>
          public static string DESDecrypt(string DecryptString, string DecryptKey)
          {
              if (string.IsNullOrEmpty(DecryptString)) { throw (new Exception("密文不得为空")); }
 
              if (string.IsNullOrEmpty(DecryptKey)) { throw (new Exception("密钥不得为空")); }
 
              if (DecryptKey.Length != 8) { throw (new Exception("密钥必须为8位")); }
 
              byte[] m_btIV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
 
              string m_strDecrypt = "";
 
              DESCryptoServiceProvider m_DESProvider = new DESCryptoServiceProvider();
 
              try
              {
                  byte[] m_btDecryptString = Convert.FromBase64String(DecryptString);
 
                  MemoryStream m_stream = new MemoryStream();
 
                  CryptoStream m_cstream = new CryptoStream(m_stream, m_DESProvider.CreateDecryptor(Encoding.Default.GetBytes(DecryptKey), m_btIV), CryptoStreamMode.Write);
 
                  m_cstream.Write(m_btDecryptString, 0, m_btDecryptString.Length);
 
                  m_cstream.FlushFinalBlock();
 
                  m_strDecrypt = Encoding.Default.GetString(m_stream.ToArray());
 
                  m_stream.Close(); m_stream.Dispose();
 
                  m_cstream.Close(); m_cstream.Dispose();
              }
              catch (IOException ex) { throw ex; }
              catch (CryptographicException ex) { throw ex; }
              catch (ArgumentException ex) { throw ex; }
              catch (Exception ex) { throw ex; }
              finally { m_DESProvider.Clear(); }
 
              return m_strDecrypt;
          }*/


        /// <summary>
        /// RC2 加密(用变长密钥对大量数据进行加密)
        /// </summary>
        /// <param name="EncryptString">待加密密文</param>
        /// <param name="EncryptKey">加密密钥</param>
        /// <returns>returns</returns>
        public static string RC2Encrypt(string EncryptString, string EncryptKey)
        {
            if (string.IsNullOrEmpty(EncryptString)) { throw (new Exception("密文不得为空")); }

            if (string.IsNullOrEmpty(EncryptKey)) { throw (new Exception("密钥不得为空")); }

            if (EncryptKey.Length < 5 || EncryptKey.Length > 16) { throw (new Exception("密钥必须为5-16位")); }

            string m_strEncrypt = "";

            byte[] m_btIV = { 0x78, 0x90, 0xAB, 0x12, 0x34, 0x56, 0xCD, 0xEF };

            RC2CryptoServiceProvider m_RC2Provider = new RC2CryptoServiceProvider();

            try
            {
                byte[] m_btEncryptString = Encoding.Default.GetBytes(EncryptString);

                MemoryStream m_stream = new MemoryStream();

                CryptoStream m_cstream = new CryptoStream(m_stream, m_RC2Provider.CreateEncryptor(Encoding.Default.GetBytes(EncryptKey), m_btIV), CryptoStreamMode.Write);

                m_cstream.Write(m_btEncryptString, 0, m_btEncryptString.Length);

                m_cstream.FlushFinalBlock();

                m_strEncrypt = Convert.ToBase64String(m_stream.ToArray());

                m_stream.Close(); m_stream.Dispose();

                m_cstream.Close(); m_cstream.Dispose();
            }
            catch (IOException ex) { throw ex; }
            catch (CryptographicException ex) { throw ex; }
            catch (ArgumentException ex) { throw ex; }
            catch (Exception ex) { throw ex; }
            finally { m_RC2Provider.Clear(); }

            return m_strEncrypt;
        }


        /// <summary>
        /// RC2 解密(用变长密钥对大量数据进行加密)
        /// </summary>
        /// <param name="DecryptString">待解密密文</param>
        /// <param name="DecryptKey">解密密钥</param>
        /// <returns>returns</returns>
        public static string RC2Decrypt(string DecryptString, string DecryptKey)
        {
            if (string.IsNullOrEmpty(DecryptString)) { throw (new Exception("密文不得为空")); }

            if (string.IsNullOrEmpty(DecryptKey)) { throw (new Exception("密钥不得为空")); }

            if (DecryptKey.Length < 5 || DecryptKey.Length > 16) { throw (new Exception("密钥必须为5-16位")); }

            byte[] m_btIV = { 0x78, 0x90, 0xAB, 0x12, 0x34, 0x56, 0xCD, 0xEF };

            string m_strDecrypt = "";

            RC2CryptoServiceProvider m_RC2Provider = new RC2CryptoServiceProvider();

            try
            {
                byte[] m_btDecryptString = Convert.FromBase64String(DecryptString);

                MemoryStream m_stream = new MemoryStream();

                CryptoStream m_cstream = new CryptoStream(m_stream, m_RC2Provider.CreateDecryptor(Encoding.Default.GetBytes(DecryptKey), m_btIV), CryptoStreamMode.Write);

                m_cstream.Write(m_btDecryptString, 0, m_btDecryptString.Length);

                m_cstream.FlushFinalBlock();

                m_strDecrypt = Encoding.Default.GetString(m_stream.ToArray());

                m_stream.Close(); m_stream.Dispose();

                m_cstream.Close(); m_cstream.Dispose();
            }
            catch (IOException ex) { throw ex; }
            catch (CryptographicException ex) { throw ex; }
            catch (ArgumentException ex) { throw ex; }
            catch (Exception ex) { throw ex; }
            finally { m_RC2Provider.Clear(); }

            return m_strDecrypt;
        }

        /// <summary>
        /// 3DES 加密(基于DES,对一块数据用三个不同的密钥进行三次加密,强度更高)
        /// </summary>
        /// <param name="EncryptString">待加密密文</param>
        /// <param name="EncryptKey1">密钥一</param>
        /// <param name="EncryptKey2">密钥二</param>
        /// <param name="EncryptKey3">密钥三</param>
        /// <returns>returns</returns>
        public static string DES3Encrypt(string EncryptString, string EncryptKey1, string EncryptKey2, string EncryptKey3)
        {
            string m_strEncrypt = "";

            try
            {
                m_strEncrypt = DESEncrypt(EncryptString, EncryptKey3);

                m_strEncrypt = DESEncrypt(m_strEncrypt, EncryptKey2);

                m_strEncrypt = DESEncrypt(m_strEncrypt, EncryptKey1);
            }
            catch (Exception ex) { throw ex; }

            return m_strEncrypt;
        }
        /// <summary>
        /// 3DES 解密(基于DES,对一块数据用三个不同的密钥进行三次加密,强度更高)
        /// </summary>
        /// <param name="DecryptString">待解密密文</param>
        /// <param name="DecryptKey1">密钥一</param>
        /// <param name="DecryptKey2">密钥二</param>
        /// <param name="DecryptKey3">密钥三</param>
        /// <returns>returns</returns>
        public static string DES3Decrypt(string DecryptString, string DecryptKey1, string DecryptKey2, string DecryptKey3)
        {
            string m_strDecrypt = "";

            try
            {
                m_strDecrypt = DESDecrypt(DecryptString, DecryptKey1);

                m_strDecrypt = DESDecrypt(m_strDecrypt, DecryptKey2);

                m_strDecrypt = DESDecrypt(m_strDecrypt, DecryptKey3);
            }
            catch (Exception ex) { throw ex; }

            return m_strDecrypt;
        }


        /// <summary>
        /// AES 加密(高级加密标准,是下一代的加密算法标准,速度快,安全级别高,目前 AES 标准的一个实现是 Rijndael 算法)
        /// </summary>
        /// <param name="EncryptString">待加密密文</param>
        /// <param name="EncryptKey">加密密钥</param>
        /// <returns></returns>
        public static string AESEncrypt(string EncryptString, string EncryptKey)
        {
            if (string.IsNullOrEmpty(EncryptString)) { throw (new Exception("密文不得为空")); }

            if (string.IsNullOrEmpty(EncryptKey)) { throw (new Exception("密钥不得为空")); }

            string m_strEncrypt = "";

            byte[] m_btIV = Convert.FromBase64String("Rkb4jvUy/ye7Cd7k89QQgQ==");

            Rijndael m_AESProvider = Rijndael.Create();

            try
            {
                byte[] m_btEncryptString = Encoding.Default.GetBytes(EncryptString);

                MemoryStream m_stream = new MemoryStream();

                CryptoStream m_csstream = new CryptoStream(m_stream, m_AESProvider.CreateEncryptor(Encoding.Default.GetBytes(EncryptKey), m_btIV), CryptoStreamMode.Write);

                m_csstream.Write(m_btEncryptString, 0, m_btEncryptString.Length);

                m_csstream.FlushFinalBlock();

                m_strEncrypt = Convert.ToBase64String(m_stream.ToArray());

                m_stream.Close(); m_stream.Dispose();

                m_csstream.Close(); m_csstream.Dispose();
            }
            catch (IOException ex) { throw ex; }
            catch (CryptographicException ex) { throw ex; }
            catch (ArgumentException ex) { throw ex; }
            catch (Exception ex) { throw ex; }
            finally { m_AESProvider.Clear(); }

            return m_strEncrypt;
        }
        /// <summary>
        /// AES 解密(高级加密标准,是下一代的加密算法标准,速度快,安全级别高,目前 AES 标准的一个实现是 Rijndael 算法)
        /// </summary>
        /// <param name="DecryptString">待解密密文</param>
        /// <param name="DecryptKey">解密密钥</param>
        /// <returns></returns>
        public static string AESDecrypt(string DecryptString, string DecryptKey)
        {
            if (string.IsNullOrEmpty(DecryptString)) { throw (new Exception("密文不得为空")); }

            if (string.IsNullOrEmpty(DecryptKey)) { throw (new Exception("密钥不得为空")); }

            string m_strDecrypt = "";

            byte[] m_btIV = Convert.FromBase64String("Rkb4jvUy/ye7Cd7k89QQgQ==");

            Rijndael m_AESProvider = Rijndael.Create();

            try
            {
                byte[] m_btDecryptString = Convert.FromBase64String(DecryptString);

                MemoryStream m_stream = new MemoryStream();

                CryptoStream m_csstream = new CryptoStream(m_stream, m_AESProvider.CreateDecryptor(Encoding.Default.GetBytes(DecryptKey), m_btIV), CryptoStreamMode.Write);

                m_csstream.Write(m_btDecryptString, 0, m_btDecryptString.Length);

                m_csstream.FlushFinalBlock();

                m_strDecrypt = Encoding.Default.GetString(m_stream.ToArray());

                m_stream.Close(); m_stream.Dispose();

                m_csstream.Close(); m_csstream.Dispose();
            }
            catch (IOException ex) { throw ex; }
            catch (CryptographicException ex) { throw ex; }
            catch (ArgumentException ex) { throw ex; }
            catch (Exception ex) { throw ex; }
            finally { m_AESProvider.Clear(); }

            return m_strDecrypt;
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
DES加密解密算法是一种对称加密算法,在Java中可以使用JDK自带的Cipher类实现。下面是一个简单的示例代码: ```java import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.security.NoSuchAlgorithmException; import java.util.Base64; public class DesDemo { private static final String KEY_ALGORITHM = "DES"; private static final String CIPHER_ALGORITHM = "DES/ECB/PKCS5Padding"; public static String encrypt(String content, String password) throws Exception { SecretKey secretKey = generateKey(password); Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] encryptedBytes = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8)); return Base64.getEncoder().encodeToString(encryptedBytes); } public static String decrypt(String content, String password) throws Exception { SecretKey secretKey = generateKey(password); Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, secretKey); byte[] encryptedBytes = Base64.getDecoder().decode(content); byte[] decryptedBytes = cipher.doFinal(encryptedBytes); return new String(decryptedBytes, StandardCharsets.UTF_8); } private static SecretKey generateKey(String password) throws NoSuchAlgorithmException { KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM); keyGenerator.init(56); return new SecretKeySpec(password.getBytes(StandardCharsets.UTF_8), KEY_ALGORITHM); } public static void main(String[] args) throws Exception { String content = "Hello, World!"; String password = "12345678"; String encryptedContent = encrypt(content, password); String decryptedContent = decrypt(encryptedContent, password); System.out.println("明文:" + content); System.out.println("密文:" + encryptedContent); System.out.println("解密后:" + decryptedContent); } } ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值