我正在通过SymmetricCryptograper
加密用户信息,并将其放入JWT中。但是,当我用加密的信息回叫该令牌并尝试解密这些信息时,我得到了奇怪的字符。
因此,我遍历了StackOverflow,发现真正的问题可能与缺少Encoding.UTF8
有关,因此我将它们放在StreamWriter
中的StreamReader
和Encrypt
实例上和Decrypt
方法。但是,这并不是很不幸。
这是我的类,其中包含Encrypt和Decrypt方法。
public class DESCryptographer : SymmetricCryptographer
{
private readonly DESCryptoServiceProvider _des = new DESCryptoServiceProvider();
public DESCryptographer(string key) : base(key)
{
_des.GenerateIV();
IV = _des.IV;
}
public DESCryptographer(string key, string iV) : base(key, Encoding.UTF8.GetBytes(iV))
{
}
public override string Encrypt(string plainText)
{
MemoryStream memoryStream = new MemoryStream();
ICryptoTransform cEncryptor = _des.CreateEncryptor(Encoding.UTF8.GetBytes(Key), IV);
CryptoStream cryptoStream = new CryptoStream(memoryStream,
cEncryptor, CryptoStreamMode.Write);
StreamWriter writer = new StreamWriter(cryptoStream, Encoding.UTF8);
writer.Write(plainText);
writer.Flush();
cryptoStream.FlushFinalBlock();
writer.Flush();
return Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
}
public override string Decrypt(string encryptedText)
{
MemoryStream memoryStream = new MemoryStream
(Convert.FromBase64String(encryptedText));
ICryptoTransform cDecryptor = _des.CreateDecryptor(Encoding.UTF8.GetBytes(Key), IV);
CryptoStream cryptoStream = new CryptoStream(memoryStream,
cDecryptor, CryptoStreamMode.Read);
StreamReader reader = new StreamReader(cryptoStream, Encoding.UTF8);
return reader.ReadToEnd();
}
}
下面是我发布JWT的课程:
public string PublishToken(string email, string password, string digitCode, int expireMinutes, int notBeforeMinutes)
{
var hmac = new HMACSHA256();
var key = Convert.ToBase64String(hmac.Key);
var symmetricKey = Convert.FromBase64String(key);
var tokenHandler = new JwtSecurityTokenHandler();
var now = DateTime.Now;
SymmetricCryptograperManager symmetricCryptograperManager = new SymmetricCryptograperManager();
var schema = symmetricCryptograperManager.GetSymmetricCryptographer(SymmetricCryptographyStrategy.DESCryptography, "000" + digitCode);
string encryptedEmail = schema.Encrypt(email);
string encryptedPassword = schema.Encrypt(password);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Email, encryptedEmail),
new Claim(ClaimTypes.Hash, encryptedPassword),
new Claim(ClaimTypes.SerialNumber, digitCode)
}),
NotBefore = now.AddMinutes(Convert.ToInt32(notBeforeMinutes)),
Expires = now.AddMinutes(Convert.ToInt32(expireMinutes)),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(symmetricKey), SecurityAlgorithms.HmacSha256Signature)
};
var stoken = tokenHandler.CreateToken(tokenDescriptor);
var token = tokenHandler.WriteToken(stoken);
return token;
}
最后,下面是我的令牌认证类。
public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
{
SymmetricCryptograperManager symmetricCryptograperManager = new SymmetricCryptograperManager();
HttpRequestMessage request = context.Request;
AuthenticationHeaderValue authorization = request.Headers.Authorization;
if (authorization == null)
{
return;
}
if (authorization.Scheme != "Basic")
{
return;
}
if (String.IsNullOrEmpty(authorization.Parameter))
{
context.ErrorResult = new AuthenticationFailureResult("Missing Credentials", request);
return;
}
byte[] credentialBytes;
string parameter = authorization.Parameter;
string[] converted = parameter.Split('.');
credentialBytes = Convert.FromBase64String(converted[1]);
Encoding encoding = Encoding.UTF8;
encoding = (Encoding)encoding.Clone();
encoding.DecoderFallback = DecoderFallback.ExceptionFallback;
string decodedCredentials;
decodedCredentials = encoding.GetString(credentialBytes);
if (String.IsNullOrEmpty(decodedCredentials))
{
return;
}
int colonIndex = decodedCredentials.IndexOf(':');
if (colonIndex == -1)
{
return;
}
string[] colonArray = decodedCredentials.Split('"');
string encrpytedEmail = colonArray[3];
string encryptedPassword = colonArray[7];
string digitCode = colonArray[11];
var schema = symmetricCryptograperManager.GetSymmetricCryptographer(SymmetricCryptographyStrategy.DESCryptography, "000" + digitCode);
string email = schema.Decrypt(encrpytedEmail);
string password = schema.Decrypt(encryptedPassword);
Tuple<string, string> emailAndPassword = new Tuple<string, string>(email, password);
//authentication codes continues..
}
我在这些类上设置了断点,以检查发送到数据库和从数据库接收的加密数据是否相同。是的,它们是相同的。
这是我从schema.Decrypt(encrpytedEmail)
得到的:
h \0��\u0018���547@gmail.com
预期为:ozgur547@gmail.com
谢谢!
答案 0 :(得分:0)
您尚未正确实施IV处理。您确实不想重复使用加密算法或XCryptoServiceProvicer
,并且没有必要。只要记住秘密密钥,您就可以生成这些轻量对象中的另一个。 IV应该与密文一起存储;当前,第一段明文表示在加密/解密过程中使用了不同的IV值。
当然,DES不是现代的密码原语;尝试AES。我可以尝试开始解释加密货币,以及如何在能够抵御特定攻击情形下的攻击的协议中描述您的代码,但这对StackOverflow而言(对于我而言,这太浪费了)。
当心包装器类,这些包装器类只存在于您对密码的理解中。您肯定以后会怀疑为什么要首先写它们。