Java C# 共用 AES-128 加密

Java AES-128 加密:

 /**
   * Aes 加密
   * @param content 加密内容
   * @param key 秘钥
   * @return
   * @throws Exception
   */
 public static String Encrypt(String content, String key) throws Exception {
    byte[] raw = key.getBytes("utf-8");
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/补码方式"
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    byte[] encrypted = cipher.doFinal(content.getBytes("utf-8"));
        
    //此处使用BASE64做转码功能,同时能起到2次加密的作用。
    return new Base64().encodeToString(encrypted);
}
    
/**
  * AES解密
  * @param content 解密内容
  * @param key 秘钥
  * @return
  * @throws Exception
  */
public static String Decrypt(String content, String key) throws Exception {
    try {
          byte[] raw = key.getBytes("utf-8");
          SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
          Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
          cipher.init(Cipher.DECRYPT_MODE, skeySpec);
          byte[] encrypted1 = new Base64().decode(content);//先用base64解密
          try {
                byte[] original = cipher.doFinal(encrypted1);
                String originalString = new String(original,"utf-8");
                return originalString;
          } catch (Exception e) {
                System.out.println(e.toString());
                return null;
          }
    } catch (Exception ex) {
          System.out.println(ex.toString());
          return null;
    }
}

C# AES-128 加密:

/*
 *  AES加密 
 * */
public static string Encrypt(string toEncrypt, string key)
{
    byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key);
    byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);

    RijndaelManaged rDel = new RijndaelManaged();
    rDel.Key = keyArray;
    rDel.Mode = CipherMode.ECB;
    rDel.Padding = PaddingMode.PKCS7;

    ICryptoTransform cTransform = rDel.CreateEncryptor();
    byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

    return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}

/*
 * AES解密
 * */
public static string Decrypt(string toDecrypt, string key)
{
    byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key);
    byte[] toEncryptArray = Convert.FromBase64String(toDecrypt);

    RijndaelManaged rDel = new RijndaelManaged();
    rDel.Key = keyArray;
    rDel.Mode = CipherMode.ECB;
    rDel.Padding = PaddingMode.PKCS7;

    ICryptoTransform cTransform = rDel.CreateDecryptor();
    byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

    return UTF8Encoding.UTF8.GetString(resultArray);
}

你可能感兴趣的:(Java C# 共用 AES-128 加密)