没有依赖关系的简单字符串加密
本文关键字:简单 字符串 加密 关系 依赖 | 更新日期: 2023-09-27 18:01:22
我需要一个简单的算法来加密/解密字符串。有点像Base64,但更安全一点。这不是关键任务。我只需要一些字符串操作。不像复制字符串并使用简单的base 64解码器使其可读那么简单。
为什么不使用AES?
由于我的应用程序是使用。net Core创建的,它运行在windows和mac上。我面临的问题是,为了在mac上使用System.Security
,我需要安装openssl。因为我没有sudo访问权限,我不能安装它。
要求如下:
- 简单字符串加密
- 不依赖于
System.Security.*
我读过Simple不安全的双向"混淆";
如果您正在寻找混淆而不是安全性,您可以使用常量或用常量种子初始化的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 ())
- 3 des (System.Security.Cryptography.TripleDES.Create ())
对于非对称加密
- RSA (System.Security.Cryptography.RSA.Create ())
看来你至少需要System.Security
。
EDIT:这里有一个很好的SO问题,有大量与加密相关的函数。注意System.Security
名称空间类和方法的广泛使用。
使用XTEA,实际上是相当安全的。
以下是维基百科的完整源代码:
#include <stdint.h>
/* 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;
}
Something with bitshift:
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));
加密:4 zsa4aia4ama4boa4kca4ama4boa4kwa4kaa4k + A4KiA4K + A4KCA4ZSA4a + A4bCA4ZOA4aWA4aOA4bKA4aWA4bSA4KCA4LGA4LGA4LGA4KGA4KGA
解密:
这是%&/(/TopSecret 111!!
注意
不是很漂亮,也很简单。您可以调整盐和编码,以满足您的需要。
欢呼