仿射密码C#
时间: 2023-07-12 13:14:56 浏览: 48
以下是 C# 实现的仿射密码算法:
```csharp
public static string AffineCipher(string text, int a, int b)
{
// 取模数,保证加密后的字符在 26 个字母范围内
int m = 26;
// 将明文转换为大写字母
text = text.ToUpper();
string cipherText = "";
foreach (char c in text)
{
if (Char.IsLetter(c))
{
// 将字符转换为数字
int x = (int)(c - 'A');
// 计算加密后的数字
int y = (a * x + b) % m;
// 将数字转换为字符
char cipherChar = (char)(y + 'A');
cipherText += cipherChar;
}
else
{
cipherText += c;
}
}
return cipherText;
}
```
其中,`text` 是要加密的明文,`a` 和 `b` 是加密密钥。
使用方法如下:
```csharp
string text = "Hello World";
int a = 3;
int b = 7;
string cipherText = AffineCipher(text, a, b);
Console.WriteLine(cipherText);
```
输出结果为:`KHOOR ZRUOG`。