现在的位置: 首页 > 综合 > 正文

Android 与C# DES+Base64加密的互通

2018年05月06日 ⁄ 综合 ⁄ 共 1499字 ⁄ 字号 评论关闭

java代码:

 public static String encryptForDES(Stringsouce, String key) throws InvalidKeyException,NoSuchAlgorithmException, InvalidKeySpecException,NoSuchPaddingException, IllegalBlockSizeException,
    BadPaddingException,UnsupportedEncodingException {
    //DES算法要求有一个可信任的随机数源
    SecureRandom sr = newSecureRandom();
    //从原始密匙数据创建DESKeySpec对象
    DESKeySpec dks = newDESKeySpec(key.getBytes());
    //创建一个密匙工厂,然后用它把DESKeySpec转换成 一个SecretKey对象
    SecretKeyFactorykeyFactory = SecretKeyFactory.getInstance("DES");
    SecretKey key1 =keyFactory.generateSecret(dks);
    //Cipher对象实际完成加密操作
    Cipher cipher =Cipher.getInstance("DES");
    // 用密匙初始化Cipher对象
   cipher.init(Cipher.ENCRYPT_MODE, key1, sr);
    // 现在,获取数据并加密
    byte encryptedData[] =cipher.doFinal(souce.getBytes());
    //通过BASE64位编码成字符创形式
    
    return newString(Base64.encode(encryptedData, Base64.DEFAULT),"UTF-8");
    }
C#代码:
using System.Security.Cryptography;
using System.IO;
// des加密函数
public string Encrypt(string pToEncrypt, string sKey)
{
// 创建des加密没
using (DESCryptoServiceProvider des = newDESCryptoServiceProvider())
{
// 得到UTF-8的数据源
byte[] inputByteArray =Encoding.UTF8.GetBytes(pToEncrypt);
// 设置key和iv密钥
des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
//由于java是使用默认加密模式,C#默认是CBC,需要修改为ECB
des.Mode =CipherMode.ECB;
// 创建数据流并进行加密
MemoryStream ms = new MemoryStream();
using (CryptoStream cs = new CryptoStream(ms,des.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
cs.Close();
}
// 关闭数据流
ms.Close();
return Convert.ToBase64String(ms.ToArray());
}
}

抱歉!评论已关闭.