美文网首页
java c#配套加密解密aes算法

java c#配套加密解密aes算法

作者: 吉凶以情迁 | 来源:发表于2024-05-23 16:38 被阅读0次

java中必须用Base64.NO_WRAP不生成换行,否则base64在c#那边无法解密

    public static String encrypt(String data, byte[] key, byte[] iv, long expirationTime) throws Exception {
        long timestamp = expirationTime;
        if (timestamp > 0) {
            char timeFlag = '\uffff';
            data += timeFlag + timestamp;
        }

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(iv);

        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivSpec);

        byte[] encryptedData = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
        return android.util.Base64.encodeToString(encryptedData,  Base64.NO_WRAP);
    }

    public static String decrypt(String encryptedDataStr, byte[] key, byte[] iv) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(iv);

        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivSpec);

        byte[] encryptedData = android.util.Base64.decode(encryptedDataStr, Base64.NO_WRAP);
        byte[] decryptedData = cipher.doFinal(encryptedData);

        String decryptedText = new String(decryptedData, StandardCharsets.UTF_8);
        char timeFlag = '\uffff';
        int index = decryptedText.lastIndexOf(timeFlag);
        if (index <= 0) {
            return decryptedText;
        } else {
            String timeStr = decryptedText.substring(index + 1);
            long timestamp = Long.parseLong(timeStr);
            if (System.currentTimeMillis() > timestamp) {
                return null;
            }
            decryptedText.substring(0, index);
            return decryptedText;
        }

//        String timeStr = decryptedText.substring(index + 1);
 /*       long timestamp = Long.parseLong(timeStr);
        Instant expirationTime = Instant.ofEpochSecond(timestamp);

        if (expirationTime.isBefore(Instant.now())) {
            return null;
        }*/

        // return decryptedText.substring(0, index);
    }

c#代码

  public static string Encrypt(string data, byte[] key, byte[] iv, DateTime expirationTime)
        {


            DateTimeOffset dateTimeOffset = new DateTimeOffset(expirationTime);
            long timestamp = dateTimeOffset.ToUnixTimeSeconds(); // 转换为秒级时间
            if (expirationTime != null)
            {
                data = data + char.MaxValue + timestamp;
            }
            // 要加密的字符串

            // 生成密钥
            /*        byte[] key = Encoding.UTF8.GetBytes("0123456789abcdef");

                    // 生成 IV(初始化向量)
                    byte[] iv = Encoding.UTF8.GetBytes("fedcba9876543210");*/

            // 创建 AES 算法的实例
            using (Aes aes1 = Aes.Create())
            {
                // 设置算法的属性
                aes1.Key = key;
                aes1.IV = iv;

                // 创建加密器
                ICryptoTransform encryptor = aes1.CreateEncryptor();

                // 将字符串转换为字节数组
                byte[] data1 = Encoding.UTF8.GetBytes(data);

                // 加密数据
                byte[] encryptedData = encryptor.TransformFinalBlock(data1, 0, data1.Length);

                // 将加密后的数据转换为字符串
                string ciphertext = Convert.ToBase64String(encryptedData);
                return ciphertext;

            }

        }

        public static string? Decrypt(string data, byte[] key, byte[] iv)
        {

            using (Aes aes1 = Aes.Create())
            {
                // 设置算法的属性
                aes1.Key = key;
                aes1.IV = iv;

                // 创建加密器
                ICryptoTransform encryptor = aes1.CreateEncryptor();

                // 将字符串转换为字节数组
                byte[] data1 = Encoding.UTF8.GetBytes(data);

                // 创建解密器
                ICryptoTransform decryptor = aes1.CreateDecryptor();

                // 将加密后的数据转换为字节数组
                byte[] encryptedData2 = Convert.FromBase64String(data);

                // 解密数据
                byte[] decryptedData = decryptor.TransformFinalBlock(encryptedData2, 0, encryptedData2.Length);

                // 将解密后的数据转换为字符串
                string decryptedText = Encoding.UTF8.GetString(decryptedData);
                int i = decryptedText.LastIndexOf(char.MaxValue);
                if (i <= 0)
                {
                    return decryptedText;
                }
                string time = decryptedText.Substring(i + 1);
                long timestap = long.Parse(time);

                DateTimeOffset expirationTime = DateTimeOffset.FromUnixTimeSeconds(timestap);
                if (expirationTime.LocalDateTime < DateTime.Now)
                {
                    return null;
                }
                string content = decryptedText.Substring(0, i);
                return content;
            }
        }

相关文章

网友评论

      本文标题:java c#配套加密解密aes算法

      本文链接:https://www.haomeiwen.com/subject/mtbtqjtx.html