没有依赖关系的简单字符串加密

我需要一个简单的算法来加密/解密字符串。 像Base64这样的东西,但更安全一点。 这不是关键任务。 我只需要一些字符串操作。 不像复制字符串那么容易,并且使用简单的base 64解码器使其可读。

为什么不使用AES?

由于我的应用程序是使用.NET Core创建的,因此它可以在Windows和Mac上运行。 我面临的问题是,为了在mac上使用System.Security ,我需要安装openssl。 由于我没有sudo访问权限,我无法安装它。

所以这里是要求:

  • 简单的字符串加密
  • 没有依赖System.Security.*

我已经为C#阅读了简单的不安全的双向“混淆”,但没有依赖的解决方案。

如果您正在寻找混淆而不是安全性,则可以使用常量或使用常量种子初始化的PRNG的输出对字符串进行异或。

常量示例:

 byte xorConstant = 0x53; string input = "foo"; byte[] data = Encoding.UTF8.GetBytes(input); for (int i = 0; i < data.Length; i++) { data[i] = (byte)(data[i] ^ xorConstant) } string output = Convert.ToBase64String(data); 

要解码:

 byte xorConstant = 0x53; byte[] data = Convert.FromBase64String(input); for (int i = 0; i < data.Length; i++) { data[i] = (byte)(data[i] ^ xorConstant) } string plainText = Encoding.UTF8.GetString(data); 

所有非对称和对称加密方法都驻留在System.Security命名空间中。 从这个SO回答 :

.NET Core中提供的对称加密选项包括:

  • AES(System.Security.Cryptography.Aes.Create())
  • 3DES(System.Security.Cryptography.TripleDES.Create())

对于非对称加密

  • RSA(System.Security.Cryptography.RSA.Create())

所以看起来你至少需要System.Security

编辑 : 这是一个很好的问题,有很多与加密相关的function。 请注意System.Security命名空间类和方法的广泛使用。

使用XTEA ,它实际上是相当安全的。

以下是维基百科的完整源代码:

 #include  /* take 64 bits of data in v[0] and v[1] and 128 bits of key[0] - key[3] */ void encipher(unsigned int num_rounds, uint32_t v[2], uint32_t const key[4]) { unsigned int i; uint32_t v0=v[0], v1=v[1], sum=0, delta=0x9E3779B9; for (i=0; i < num_rounds; i++) { v0 += (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (sum + key[sum & 3]); sum += delta; v1 += (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (sum + key[(sum>>11) & 3]); } v[0]=v0; v[1]=v1; } void decipher(unsigned int num_rounds, uint32_t v[2], uint32_t const key[4]) { unsigned int i; uint32_t v0=v[0], v1=v[1], delta=0x9E3779B9, sum=delta*num_rounds; for (i=0; i < num_rounds; i++) { v1 -= (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (sum + key[(sum>>11) & 3]); sum -= delta; v0 -= (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (sum + key[sum & 3]); } v[0]=v0; v[1]=v1; } 

BitShifting的东西:

  var topSecret = "This is%&/(/ TopSecret 111!!"; int shft = 5; string encrypted = topSecret.Select(ch => ((int) ch) << shft).Aggregate("", (current, val) => current + (char) (val*2)); encrypted = Convert.ToBase64String(Encoding.UTF8.GetBytes(encrypted)); string decrypted = Encoding.UTF8.GetString(Convert.FromBase64String(encrypted)).Select(ch => ((int) ch) >> shft).Aggregate("", (current, val) => current + (char) (val/2)); 

加密:

4ZSA4aiA4amA4bOA4KCA4amA4bOA4KWA4KaA4K + A4KiA4K + A4KCA4ZSA4a + A4bCA4ZOA4aWA4aOA4bKA4aWA4bSA4KCA4LGA4LGA4LGA4KGA4KGA

再次解密:

这是%&/(/ TopSecret 111 !!

注意

不是很漂亮,也很小。 您可以调整盐和编码以满足您的需求。

干杯