C#.NET与JAVA互通之DES加密V2024

本文涉及的产品
密钥管理服务KMS,1000个密钥,100个凭据,1个月
简介: C#,JAVA,DES

C#.NET与JAVA互通之DES加密V2024

环境:
.NET Framework 4.6 控制台程序
JAVA这边:JDK8 (1.8) 控制台程序

注意点:

1.由于密钥、明文、密文的输入输出参数,都是byte数组(byte[]),所以:字符串转byte数组(byte[])环节,双方要约定好编码。

  1. KEY 和 IV 从字符串转byte数组(byte[])时,双方要约定好编码,一般是UTF8。

3.明文从字符串转byte数组(byte[])时,双方要约定好编码,一般是UTF8,.NET 这边要注意:不能用 Encoding.Default。

4.加密后的结果,从byte数组(byte[])转字符串时,双方要约定好编码,一般是Base64字符串。

5.NET 的PKCS7Padding 对应 JAVA 的:PKCS5Padding

一、 .NET DES

先看工具类:DesUtil

using System;
using System.Security.Cryptography;
using System.Text;

namespace CommonUtils
{
   
   
    /// <summary>
    /// 工具类,2024-06-16,runliuv。
    /// </summary>
    public class DesUtil
    {
   
   
        public static byte[] DesEncryptCBC(byte[] plainText, byte[] Key, byte[] IV)
        {
   
   
            byte[] encrypted;

            using (DESCryptoServiceProvider desAlg = new DESCryptoServiceProvider())
            {
   
   
                desAlg.Key = Key;
                desAlg.IV = IV;
                desAlg.Mode = CipherMode.CBC;
                desAlg.Padding = PaddingMode.PKCS7;

                using (ICryptoTransform encryptor = desAlg.CreateEncryptor())
                {
   
   
                    encrypted= encryptor.TransformFinalBlock(plainText, 0, plainText.Length);
                }
            }

            return encrypted;
        }

        public static byte[] DesDecryptCBC(byte[] cipherText, byte[] Key, byte[] IV) 
        {
   
   
            byte[] plaintext = null;

            using (DESCryptoServiceProvider desAlg = new DESCryptoServiceProvider())
            {
   
   
                desAlg.Key = Key;
                desAlg.IV = IV;
                desAlg.Mode = CipherMode.CBC;
                desAlg.Padding = PaddingMode.PKCS7;

                using (ICryptoTransform decryptor = desAlg.CreateDecryptor()) 
                {
   
    
                    plaintext = decryptor.TransformFinalBlock(cipherText, 0, cipherText.Length);
                }
            }

            return plaintext;
        }
        /// <summary>
        /// DES CBC 加密
        /// </summary>
        /// <param name="plainText">明文</param>
        /// <param name="Key">密钥</param>
        /// <param name="IV"></param>
        /// <returns></returns>
        public static string DesEncryptCBC(string plainText, string Key, string IV)
        {
   
   
            byte[] yy= DesEncryptCBC(Encoding.UTF8.GetBytes(plainText), Encoding.UTF8.GetBytes(Key), Encoding.UTF8.GetBytes(IV));
            string xx=Convert.ToBase64String(yy);
            return xx;
        }
        /// <summary>
        /// DES CBC 解密
        /// </summary>
        /// <param name="cipherText">密文</param>
        /// <param name="Key">密钥</param>
        /// <param name="IV"></param>
        /// <returns></returns>
        public static string DesDecryptCBC(string cipherText, string Key, string IV)
        {
   
   
            byte[] yy = DesDecryptCBC(Convert.FromBase64String(cipherText), Encoding.UTF8.GetBytes(Key), Encoding.UTF8.GetBytes(IV));
            string xx = Encoding.UTF8.GetString(yy);
            return xx;
        }
    }
}

.NET 使用这个工具类,做DES CBC 加密 :


static void TestDesCbc()
{
   
   
    Console.WriteLine("-- Test Cbc --");
    string aesKey = "12345678";// DES 密钥长度是8位
    string aesIV = "abcdefgh";// DES IV长度是8位

    string orgStr = "hello .net 2024-06-10";
    string encryptedStr = DesUtil.DesEncryptCBC(orgStr, aesKey, aesIV);
    Console.WriteLine("加密字符串:" + encryptedStr);

    //自加,自解
    string decryptedStr = DesUtil.DesDecryptCBC(encryptedStr, aesKey, aesIV);
    Console.WriteLine("自加,自解:" + decryptedStr);
}

.NET 输出结果 :
-- Test Cbc --
加密字符串:yxEOkYM81hdv0bC1EwgCdE1JSsFyW70A
自加,自解:hello .net 2024-06-10
结束 。
.NET 结果.png
.NET 简要说明:

加密:
public static string DesEncryptCBC(string plainText, string Key, string IV)
{
byte[] yy= DesEncryptCBC(Encoding.UTF8.GetBytes(plainText), Encoding.UTF8.GetBytes(Key), Encoding.UTF8.GetBytes(IV));
string xx=Convert.ToBase64String(yy);
return xx;
}
Encoding.UTF8.GetBytes(plainText),明文字符串转byte数组 使用UTF8。

Encoding.UTF8.GetBytes(Key), Encoding.UTF8.GetBytes(IV),KEY 和 IV 转byte数组 使用UTF8。

public static byte[] DesEncryptCBC(byte[] plainText, byte[] Key, byte[] IV)
{
   
   
    byte[] encrypted;

    using (DESCryptoServiceProvider desAlg = new DESCryptoServiceProvider())
    {
   
   
        desAlg.Key = Key;
        desAlg.IV = IV;
        desAlg.Mode = CipherMode.CBC;
        desAlg.Padding = PaddingMode.PKCS7;

        using (ICryptoTransform encryptor = desAlg.CreateEncryptor())
        {
   
   
            encrypted= encryptor.TransformFinalBlock(plainText, 0, plainText.Length);
        }
    }

    return encrypted;
}

创建一个DESCryptoServiceProvider对象,指定KEY 和 IV,指定 加密模式和 PADDING。

创建加密器对象:desAlg.CreateEncryptor()。

使用 TransformFinalBlock 算出加密结果。

string xx=Convert.ToBase64String(yy); 加密后的结果转字符串时,使用Base64字符串。

解密:

public static string DesDecryptCBC(string cipherText, string Key, string IV)
{
   
   
    byte[] yy = DesDecryptCBC(Convert.FromBase64String(cipherText), Encoding.UTF8.GetBytes(Key), Encoding.UTF8.GetBytes(IV));
    string xx = Encoding.UTF8.GetString(yy);
    return xx;
}

Convert.FromBase64String(cipherText),由于加密结果集转字符串时用的base64,所以密文转byte数组时,就要用Convert.FromBase64String。
加密解密-密文-编码转换对应.png
KEY 和 IV 就不用多说了。

public static byte[] DesDecryptCBC(byte[] cipherText, byte[] Key, byte[] IV) 
{
   
   
    byte[] plaintext = null;

    using (DESCryptoServiceProvider desAlg = new DESCryptoServiceProvider())
    {
   
   
        desAlg.Key = Key;
        desAlg.IV = IV;
        desAlg.Mode = CipherMode.CBC;
        desAlg.Padding = PaddingMode.PKCS7;

        using (ICryptoTransform decryptor = desAlg.CreateDecryptor()) 
        {
   
    
            plaintext = decryptor.TransformFinalBlock(cipherText, 0, cipherText.Length);
        }
    }

    return plaintext;
}

创建一个DESCryptoServiceProvider对象,指定KEY 和 IV,指定 模式和 PADDING。

创建解密器对象:desAlg.CreateDecryptor()。

使用 TransformFinalBlock 解密出结果。

string xx = Encoding.UTF8.GetString(yy); 加密时,明文转byte[] 时用的UTF8,那解密出的明文结果,转byte数组时,也得用UTF8。
加密解密明文编码转换对应.png
可以说,解密与加密是相反的。
加密解密 编码转换 示意图.png
二、JAVA DES

还是简要封装个工具类DesUtil。

package org.runliuv;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class DesUtil {
   
   

    private static final String charset = "UTF-8";

    public static String DesEncryptCBC(String content, String key, String iv)
            throws Exception {
   
   

        //明文
        byte[] contentBytes = content.getBytes(charset);

        //DES KEY
        byte[] keyBytes = key.getBytes(charset);
        SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "DES");

        //DES IV
        byte[] initParam = iv.getBytes(charset);
        IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);

        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivParameterSpec);
        byte[] byEnd = cipher.doFinal(contentBytes);

        //加密后的byte数组转BASE64字符串
        String strEnd = Base64.getEncoder().encodeToString(byEnd);
        return strEnd;
    }

    /**
     * 解密
     * @param content
     * @param key
     * @param iv
     * @return
     * @throws Exception
     */
    public static String DesDecryptCBC(String content, String key, String iv)
            throws Exception {
   
   
        //反向解析BASE64字符串为byte数组
        byte[] encryptedBytes = Base64.getDecoder().decode(content);

        //DES KEY
        byte[] keyBytes = key.getBytes(charset);
        SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "DES");

        //DES IV
        byte[] initParam = iv.getBytes(charset);
        IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);

        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivParameterSpec);
        byte[] byEnd = cipher.doFinal(encryptedBytes);

        //加密后的byte数组直接转字符串
        String strEnd = new String(byEnd, charset);
        return strEnd;
    }


}

JAVA 使用工具类进行 DES CBC 加密,解密:

System.out.println("-- Test Cbc --");
            String aesKey = "12345678";// DES 密钥长度是8位
            String aesIV = "abcdefgh";// DES IV长度是8位

            String orgStr = "hello JAVA 2024-06-10";
            System.out.println("待加密字符串:" + orgStr);
            String encryptedStr = DesUtil.DesEncryptCBC(orgStr, aesKey, aesIV);
            System.out.println("加密后:" + encryptedStr);

            //自加,自解
            String decryptedStr = DesUtil.DesDecryptCBC(encryptedStr, aesKey, aesIV);
            System.out.println("自加,自解:" + decryptedStr);

效果:

-- Test Cbc --
待加密字符串:hello JAVA 2024-06-10
加密后:VkxvjXu1YKvQJF8MPnFvXhFzJgZI4j9I
自加,自解:hello JAVA 2024-06-10
JAVA 自加 自解.png
三、.NET 加 JAVA 解

先用.NET 对"hello .net 2024-06-10",这个字符串加密,KEY是"12345678",IV为“abcdefgh”,加密结果为:

yxEOkYM81hdv0bC1EwgCdE1JSsFyW70A

将这个串复制到JAVA代码,进行解密:

String NETStr ="yxEOkYM81hdv0bC1EwgCdE1JSsFyW70A";
System.out.println(".NET 加密后的串:" + NETStr);
String decryptedStr = DesUtil.DesDecryptCBC(NETStr, aesKey, aesIV);
System.out.println("JAVA解密:" + decryptedStr);
输出结果 :

-- Test Cbc --
.NET 加密后的串:yxEOkYM81hdv0bC1EwgCdE1JSsFyW70A
JAVA解密:hello .net 2024-06-10

.NET加JAVA解密.png

DES ECB 的加密模式,请自行探索。

目录
相关文章
|
23天前
|
存储 数据安全/隐私保护
.NET Core 究竟隐藏着怎样的神秘力量,能实现强身份验证与数据加密?
【8月更文挑战第28天】在数字化时代,数据安全与身份验证至关重要。.NET Core 提供了强大的工具,如 Identity 框架,帮助我们构建高效且可靠的身份验证系统,并支持高度定制化的用户模型和认证逻辑。此外,通过 `System.Security.Cryptography` 命名空间,.NET Core 还提供了丰富的加密算法和工具,确保数据传输和存储过程中的安全性。以下是一个简单的示例,展示如何使用 .NET Core 的 Identity 框架实现用户注册和登录功能。
30 3
|
1月前
|
C# 开发者 Windows
在VB.NET项目中使用C#编写的代码
在VB.NET项目中使用C#编写的代码
36 0
|
13天前
|
算法 Java 中间件
C#/.NET/.NET Core优质学习资料,干货收藏!
C#/.NET/.NET Core优质学习资料,干货收藏!
|
13天前
|
人工智能 开发框架 算法
C#/.NET/.NET Core技术前沿周刊 | 第 2 期(2024年8.19-8.25)
C#/.NET/.NET Core技术前沿周刊 | 第 2 期(2024年8.19-8.25)
|
13天前
|
缓存 开发框架 算法
C#/.NET这些实用的编程技巧你都会了吗?
C#/.NET这些实用的编程技巧你都会了吗?
|
17天前
|
SQL 存储 关系型数据库
C#一分钟浅谈:使用 ADO.NET 进行数据库访问
【9月更文挑战第3天】在.NET开发中,与数据库交互至关重要。ADO.NET是Microsoft提供的用于访问关系型数据库的类库,包含连接数据库、执行SQL命令等功能。本文从基础入手,介绍如何使用ADO.NET进行数据库访问,并提供示例代码,同时讨论常见问题及其解决方案,如连接字符串错误、SQL注入风险和资源泄露等,帮助开发者更好地利用ADO.NET提升应用的安全性和稳定性。
48 6
|
13天前
|
传感器 应用服务中间件 Linux
C#/.NET/.NET Core技术前沿周刊 | 第 3 期(2024年8.26-8.31)
C#/.NET/.NET Core技术前沿周刊 | 第 3 期(2024年8.26-8.31)
|
13天前
|
人工智能 算法 C#
C#/.NET/.NET Core技术前沿周刊 | 第 1 期(2024年8.12-8.18)
C#/.NET/.NET Core技术前沿周刊 | 第 1 期(2024年8.12-8.18)
|
23天前
|
JSON C# 开发者
💡探索C#语言进化论:揭秘.NET开发效率飙升的秘密武器💼
【8月更文挑战第28天】C#语言凭借其强大的功能与易用性深受开发者喜爱。伴随.NET平台演进,C#持续引入新特性,如C# 7.0的模式匹配,让处理复杂数据结构更直观简洁;C# 8.0的异步流则使异步编程更灵活高效,无需一次性加载全部数据至内存。通过示例展示了模式匹配简化JSON解析及异步流实现文件逐行读取的应用。此外,C# 8.0还提供了默认接口成员和可空引用类型等特性,进一步提高.NET开发效率与代码可维护性。随着C#的发展,未来的.NET开发将更加高效便捷。
38 1
|
13天前
|
JSON 测试技术 C#
C#/.NET/.NET Core优秀项目框架推荐榜单
C#/.NET/.NET Core优秀项目框架推荐榜单