高分求助,采用C#实现以下加解密的方法

huangdanming 2019-01-07 04:48:21
import java.security.Key;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

/**
* <desc>
* DES加解密操作对象.
* </desc>
*
* @createDate 2017-11-10
*/
public class DESEncoder {

//DES算法填充方式
public static final String ALGORITHM_DES = "DES/ECB/NoPadding";

public static void main(String[] args) throws Exception{
//项目公解密过程
String projectId = "00002345";
String encryptedPubKey = "8A53228E9B225225";
System.out.println("项目ID(key):" + projectId + " 项目密钥密文(data):" + encryptedPubKey);
String pubKey = DESEncoder.decode(projectId,encryptedPubKey);
System.out.println("解密得到项目密钥:" + pubKey);

//用户密钥生成过程
String userId = "123456";
System.out.println("项目密钥(key):" + pubKey + " 用户ID(data):" + userId);
String userKey = DESEncoder.encode(pubKey,userId);
System.out.println("加密得到用户密钥:" + userKey);


/*******************示例输出结果***********************:
项目ID(key):00002345 项目密钥密文(data):8A53228E9B225225
解密得到项目密钥:C1A1B0D0A1C2C6D5
用户ID(key):123456 项目密钥(data):C1A1B0D0A1C2C6D5
加密得到用户密钥:8BFE646AC2C36C5B
**********************************************************/

}


/**
* <desc>
* DES算法,加密.
* </desc>
*
* @param data 待加密的HEX字符串
* @param key 加密密钥,HEX字符串,长度不能够小于8位
* @return 加密字符串
* @author LewisLouis
* @createDate 2017-11-10
*/
public static String encode(String key, String data) throws Exception{
try{
//key的长度不能够小于8位字节
key = fillString(key,"0",16);
data = fillString(data,"0",16);
byte[] keyBytes = hexStrToBytes(key);
byte[] dataBytes = hexStrToBytes(data);
DESKeySpec dks = new DESKeySpec(keyBytes);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
Key secretKey = keyFactory.generateSecret(dks);
Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);

byte[] encryptedBytes = cipher.doFinal(dataBytes);
return bytesToHexStr(encryptedBytes);
} catch (Exception e){
throw new Exception(e);
}
}

/**
* <desc>
* DES算法,解密.
* </desc>
*
* @param data 待解密的HEX字符串
* @param key 解密密钥,HEX字符串,长度不能够小于8位
* @return 解密后的字符串
* @throws Exception 异常
* @author LewisLouis
* @createDate 2017-11-10
*/
public static String decode(String key,String data) throws Exception{
//key的长度不能够小于8位字节
key = fillString(key,"0",16);
data = fillString(data,"0",16);
byte[] keyBytes = hexStrToBytes(key);
byte[] dataBytes = hexStrToBytes(data);
SecureRandom sr = new SecureRandom();
DESKeySpec dks = new DESKeySpec(keyBytes);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
Key secretKey = keyFactory.generateSecret(dks);
Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedBytes = cipher.doFinal(dataBytes);
return bytesToHexStr(decryptedBytes);
}

/**
* <desc>
* 把16进制字符串转换成字节数组.
* </desc>
*
* @param hex 待转换的Hex字符串
* @return 转换得到的byte数组
* @author LewisLouis
* @createDate 2017-11-10
*/
public static byte[] hexStrToBytes(String hex) {
int len = (hex.length() / 2);
byte[] result = new byte[len];
char[] achar = hex.toCharArray();
for (int i = 0; i < len; i++) {
int pos = i * 2;
result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
}
return result;
}

/**
* <desc>
* 将单个十六进制字符转换为字节
* </desc>
*
* @param c 单个字符
* @return 转换得到的byte
* @author LewisLouis
* @createDate 2017-11-10
*/
private static byte toByte(char c) {
byte b = (byte) "0123456789ABCDEF".indexOf(c);
return b;
}

/**
* 把字节数组转换成16进制字符串
*
* @param bArray
* @return
*/
/**
* <desc>
* 把字节数组转换成16进制字符串.
* </desc>
*
* @param bArray 待转换的byte数组
* @return 转换得到的Hex字符串
* @author LewisLouis
* @createDate 2017-11-10
*/
public static String bytesToHexStr(byte[] bArray) {
if(bArray == null ){
return "";
}
StringBuffer sb = new StringBuffer(bArray.length);
String sTemp;
for (int i = 0; i < bArray.length; i++) {
sTemp = Integer.toHexString(0xFF & bArray[i]);
if (sTemp.length() < 2)
sb.append(0);
sb.append(sTemp.toUpperCase());
}
return sb.toString();
}

/**
* <desc>
* 自动后补齐字符串
* </desc>
*
* @param str 字符串
* @param supply 待填充的字符
* @param length 要求填充后达到的字符串总长度
* @return 填充后的字符串
* @author LewisLouis
* @createDate 2017-11-10
*/
public static String fillString(String str, String supply,int length) {
StringBuffer sb = new StringBuffer(str);
while (sb.length() < length) {
sb.append(supply);
}
return sb.toString();
}
}
...全文
235 2 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
无V涯 2019-01-10
  • 打赏
  • 举报
回复
给你一个地址,自己看吧,Base64加密解密+DES加密解密+MD5加密解密+3DES加密加密
https://blog.csdn.net/xu1440879014/article/details/86217750
丰云 2019-01-07
  • 打赏
  • 举报
回复
下面这是c#比较通用的des加密解密算法的实现,自己对照一下,看能不能用

        public static string DESEncode(this string encryptString, string encryptKey)
        {
            encryptKey = encryptKey.Substring(8);
            encryptKey = encryptKey.PadRight(8, ' ');
            byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
            byte[] rgbIV = DESKeys;
            byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
            DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
            MemoryStream mStream = new MemoryStream();
            CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
            cStream.Write(inputByteArray, 0, inputByteArray.Length);
            cStream.FlushFinalBlock();
            return Convert.ToBase64String(mStream.ToArray());
        }
        public static string DESDecode(this string decryptString, string decryptKey)
        {
            try
            {
                decryptKey = decryptKey.Substring(8);
                decryptKey = decryptKey.PadRight(8, ' ');
                byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey);
                byte[] rgbIV = DESKeys;
                byte[] inputByteArray = Convert.FromBase64String(decryptString);
                DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();

                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Encoding.UTF8.GetString(mStream.ToArray());
            }
            catch { return string.Empty; }
        }


62,243

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧