You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于Int32加密接口实现字符串加密并输出Base64格式?

实现思路

  • 加密流程:
    • 将输入明文字符串编码为UTF8字节数组,保证任意字符串都能正确转换无乱码
    • 对字节数组做PKCS7填充,将长度对齐到4的整数倍(C#中int占4个字节32位),方便按int拆分
    • 每4个字节转换为1个int值,调用传入的IIntEncryption.Encrypt完成单int加密
    • 所有加密后的int重新转换为字节数组拼接,最终编码为Base64字符串输出
  • 解密流程:
    • 将输入的Base64加密字符串解码为字节数组
    • 每4个字节转换为1个int值,调用传入的IIntEncryption.Decrypt完成单int解密
    • 所有解密后的int重新转换为字节数组拼接,去掉PKCS7填充
    • 将处理后的字节数组解码为UTF8字符串得到明文

完整实现代码

using System;
using System.Linq;
using System.Text;

public class StringEncryptionImpl : IStringEncryption
{
    public string Encrypt(string str, IIntEncryption intEncryption)
    {
        // 明文字符串转UTF8字节数组
        byte[] plainBytes = Encoding.UTF8.GetBytes(str);
        
        // PKCS7填充到长度为4的整数倍
        int paddingLength = 4 - (plainBytes.Length % 4);
        if (paddingLength == 4) paddingLength = 0;
        byte[] paddedBytes = new byte[plainBytes.Length + paddingLength];
        Array.Copy(plainBytes, paddedBytes, plainBytes.Length);
        for (int i = plainBytes.Length; i < paddedBytes.Length; i++)
        {
            paddedBytes[i] = (byte)paddingLength;
        }
        
        // 逐4字节转int加密
        byte[] encryptedBytes = new byte[paddedBytes.Length];
        for (int i = 0; i < paddedBytes.Length; i += 4)
        {
            int originalInt = BitConverter.ToInt32(paddedBytes, i);
            int encryptedInt = intEncryption.Encrypt(originalInt);
            byte[] tempBytes = BitConverter.GetBytes(encryptedInt);
            Array.Copy(tempBytes, 0, encryptedBytes, i, 4);
        }
        
        // 加密后字节数组转Base64输出
        return Convert.ToBase64String(encryptedBytes);
    }

    public string Decrypt(string encryptedStr, IIntEncryption intEncryption)
    {
        // Base64字符串转字节数组
        byte[] encryptedBytes = Convert.FromBase64String(encryptedStr);
        
        // 逐4字节转int解密
        byte[] decryptedPaddedBytes = new byte[encryptedBytes.Length];
        for (int i = 0; i < encryptedBytes.Length; i += 4)
        {
            int encryptedInt = BitConverter.ToInt32(encryptedBytes, i);
            int decryptedInt = intEncryption.Decrypt(encryptedInt);
            byte[] tempBytes = BitConverter.GetBytes(decryptedInt);
            Array.Copy(tempBytes, 0, decryptedPaddedBytes, i, 4);
        }
        
        // 去掉PKCS7填充
        int paddingLength = decryptedPaddedBytes.Last();
        byte[] plainBytes = decryptedPaddedBytes.Take(decryptedPaddedBytes.Length - paddingLength).ToArray();
        
        // 字节数组转明文字符串
        return Encoding.UTF8.GetString(plainBytes);
    }
}

注意事项

  • 代码默认使用系统字节序,如需跨平台兼容,可以固定使用大端/小端序完成int和字节数组的转换
  • 如果确认输入仅包含ASCII字符,可将Encoding.UTF8替换为Encoding.ASCII减小字节长度,UTF8兼容所有Unicode字符适用范围更广
  • 该实现输出为标准Base64格式,完全符合需求

内容的提问来源于stack exchange,提问作者user606521

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 05:36:02