Java与.NET DES加密解密互转[转载]

项目需要在两个系统间采用DES加密,一个系统为Java开发的,另外一个.NET开发的

在网上找了很多写法但加密出的数据两个系统都无法匹配,

在做了小修改以后终于可以用了,已经测试过

上代码

Java代码:
import javax.crypto.Cipher; 
import javax.crypto.SecretKey; 
import javax.crypto.SecretKeyFactory; 
import javax.crypto.spec.DESKeySpec; 
import javax.crypto.spec.IvParameterSpec; 


public class Des { 
private byte[] desKey;
    
    
//解密数据 
public static String decrypt(String message,String key)
throws Exception { 
        
byte[] bytesrc =convertHexString(message); 
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); 
DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
SecretKeyFactory keyFactory = 
SecretKeyFactory.getInstance("DES"); 
SecretKey secretKey = keyFactory.generateSecret(desKeySpec); 
IvParameterSpec iv = new IvParameterSpec(
key.getBytes("UTF-8")); 
        
cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
        
byte[] retByte = cipher.doFinal(bytesrc); 
return new String(retByte); 
} 
    
public static byte[] encrypt(String message, String key) 
throws Exception {
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); 
        
DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8")); 
        
SecretKeyFactory keyFactory = 
SecretKeyFactory.getInstance("DES"); 
SecretKey secretKey = keyFactory.generateSecret(desKeySpec); 
IvParameterSpec iv = 
new IvParameterSpec(key.getBytes("UTF-8")); 
cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv); 
        
return cipher.doFinal(message.getBytes("UTF-8")); 
} 
    
public static byte[] convertHexString(String ss) 
{
byte digest[] = new byte[ss.length() / 2]; 
for(int i = 0; i < digest.length; i++) 
{ 
String byteString = ss.substring(2 * i, 2 * i + 2); 
int byteValue = Integer.parseInt(byteString, 16);
digest[i] = (byte)byteValue;
} 
        
return digest; 
} 
    
    
public static void main(String[] args) throws Exception 
{ 
String key = "12345678";
String value="test1234 "; 
String jiami=java.net.URLEncoder.encode(
value, "utf-8").toLowerCase();
        
System.out.println("加密数据:"+jiami); 
String a=toHexString(encrypt(jiami, key)).toUpperCase(); 
        
        
System.out.println("加密后的数据为:"+a); 
String b=java.net.URLDecoder.decode(decrypt(a,key), "utf-8") ;
System.out.println("解密后的数据:"+b); 
        
} 
    
    
public static String toHexString(byte b[]) 
{ 
StringBuffer hexString = new StringBuffer(); 
for (int i = 0; i < b.length; i++) 
{ 
String plainText = Integer.toHexString(0xff & b[i]); 
if (plainText.length() < 2) plainText = "0" + plainText;
hexString.append(plainText);
} 
        
return hexString.toString();
} 
} 


.NET代码
using System; 
using System.Data; 
using System.Configuration; 
using System.Web; 
using System.Web.Security; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Web.UI.WebControls.WebParts; 
using System.Web.UI.HtmlControls; 
using System.Data.SqlClient; 
using System.Security.Cryptography; 
using System.IO;
using System.Text; 

public class TestDes{ 
//cookies加密密钥 
public static string DES_Key = "12345678"; 
    
#region DESEnCode DES加密 
public static string DESEnCode(string pToEncrypt, string sKey) 
{ 
pToEncrypt = HttpContext.Current.Server.UrlEncode(pToEncrypt); 
DESCryptoServiceProvider des = new DESCryptoServiceProvider(); 
byte[] inputByteArray = 
Encoding.GetEncoding("UTF-8").GetBytes(pToEncrypt); 
        
        
des.Key = ASCIIEncoding.ASCII.GetBytes(sKey); 
des.IV = ASCIIEncoding.ASCII.GetBytes(sKey); 
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(
ms, des.CreateEncryptor(), CryptoStreamMode.Write); 
        
cs.Write(inputByteArray, 0, inputByteArray.Length); 
cs.FlushFinalBlock(); 
        
StringBuilder ret = new StringBuilder(); 
foreach (byte b in ms.ToArray()) 
{ 
ret.AppendFormat("{0:X2}", b); 
} 
ret.ToString(); 
return ret.ToString(); 
} 
#endregion 
    
#region DESDeCode DES解密 
public static string DESDeCode(string pToDecrypt, string sKey) 
{ 
// HttpContext.Current.Response.Write(
//     pToDecrypt + "<br>" + sKey);
// HttpContext.Current.Response.End(); 
DESCryptoServiceProvider des = new DESCryptoServiceProvider(); 
        
byte[] inputByteArray = new byte[pToDecrypt.Length / 2]; 
for (int x = 0; x < pToDecrypt.Length / 2; x++) 
{ 
int i = (Convert.ToInt32(pToDecrypt.Substring(
x * 2, 2), 16)); 
inputByteArray[x] = (byte)i; 
} 
        
des.Key = ASCIIEncoding.ASCII.GetBytes(sKey); 
des.IV = ASCIIEncoding.ASCII.GetBytes(sKey); 
MemoryStream ms = new MemoryStream(); 
CryptoStream cs = new CryptoStream(
ms, des.CreateDecryptor(), CryptoStreamMode.Write); 
cs.Write(inputByteArray, 0, inputByteArray.Length); 
cs.FlushFinalBlock(); 
        
StringBuilder ret = new StringBuilder(); 
        
        
return HttpContext.Current.Server.UrlDecode(
System.Text.Encoding.Default.GetString(ms.ToArray()));
} 
#endregion 
    
public TestDes() 
{ 
// 
// TODO: 在此处添加构造函数逻辑 
// 
} 
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
提供的源码资源涵盖了Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 适合毕业设计、课程设计作业。这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。 所有源码均经过严格测试,可以直接运行,可以放心下载使用。有任何使用问题欢迎随时与博主沟通,第一时间进行解答!
Java中实现3DES加密解密可以使用JCE(Java Cryptography Extension)提供的API。下面是一个简单的示例代码: ```java import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESedeKeySpec; import java.nio.charset.StandardCharsets; import java.security.spec.KeySpec; public class TripleDesExample { public static void main(String[] args) throws Exception { String plainText = "Hello, world!"; String secretKey = "0123456789ABCDEFGHIGKLMN"; byte[] encryptedBytes = encrypt(plainText, secretKey); String encryptedText = new String(encryptedBytes, StandardCharsets.UTF_8); System.out.println("Encrypted text: " + encryptedText); byte[] decryptedBytes = decrypt(encryptedBytes, secretKey); String decryptedText = new String(decryptedBytes, StandardCharsets.UTF_8); System.out.println("Decrypted text: " + decryptedText); } public static byte[] encrypt(String plainText, String secretKey) throws Exception { byte[] plainBytes = plainText.getBytes(StandardCharsets.UTF_8); byte[] keyBytes = secretKey.getBytes(StandardCharsets.UTF_8); KeySpec keySpec = new DESedeKeySpec(keyBytes); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede"); SecretKey key = keyFactory.generateSecret(keySpec); Cipher cipher = Cipher.getInstance("DESede"); cipher.init(Cipher.ENCRYPT_MODE, key); return cipher.doFinal(plainBytes); } public static byte[] decrypt(byte[] encryptedBytes, String secretKey) throws Exception { byte[] keyBytes = secretKey.getBytes(StandardCharsets.UTF_8); KeySpec keySpec = new DESedeKeySpec(keyBytes); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede"); SecretKey key = keyFactory.generateSecret(keySpec); Cipher cipher = Cipher.getInstance("DESede"); cipher.init(Cipher.DECRYPT_MODE, key); return cipher.doFinal(encryptedBytes); } } ``` 在上面的示例代码中,我们使用了`DESede`算法实现了3DES加密解密。需要注意的是,密钥的长度必须是24个字节(即192位),因此我们在示例中使用了一个24个字符的字符串作为密钥。在实际应用中,我们可以使用更加安全的方式生成密钥,例如使用`KeyGenerator`类生成密钥。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值