如何在 F# 中创建可以加密字节数组的异或函数?
How can i create an xor function in F# which can encrypt a byte array?
如何在 F# 中创建可以加密字节数组的 xor 函数?我从 Github 那里得到这段代码,但它加密了一个字符串。
open System
let encrypt (word : string) =
let key = "KCQ"
[ 0..(word.Length - 1) ]
|> Seq.map (fun idx -> Convert.ToChar(Convert.ToInt32 word.[idx] ^^^ Convert.ToInt32 key.[idx % key.Length]))
|> String.Concat
[<EntryPoint>]
let main argv =
let encrypted = encrypt "IzzyDev"
printfn "Encrypted: %s" encrypted
let decrypted = encrypt encrypted
printfn "Decrypted: %s" decrypted
0
我如何修改此代码以使其加密字节数组而不是字符串?
我修改了您的示例以加密字节数组而不是字符串:
let toBytes (str : string) =
System.Text.Encoding.ASCII.GetBytes(str)
let encrypt (bytes : byte[]) =
let key = toBytes "KCQ"
[ 0..(bytes.Length - 1) ]
|> Seq.map (fun idx -> bytes.[idx] ^^^ key.[idx % key.Length])
|> Seq.toArray
let printBytes (bytes : byte[]) =
printf "[| "
for byte in bytes do
printf "0x%02xuy " byte
printfn "|]"
[<EntryPoint>]
let main argv =
let unencrypted = toBytes "IzzyDev"
printfn "Unencrypted:"
printBytes unencrypted
let encrypted = encrypt unencrypted
printfn "Encrypted:"
printBytes encrypted
let decrypted = encrypt encrypted
printfn "Decrypted:"
printBytes decrypted
0
输出:
Unencrypted:
[| 0x49uy 0x7auy 0x7auy 0x79uy 0x44uy 0x65uy 0x76uy |]
Encrypted:
[| 0x02uy 0x39uy 0x2buy 0x32uy 0x07uy 0x34uy 0x3duy |]
Decrypted:
[| 0x49uy 0x7auy 0x7auy 0x79uy 0x44uy 0x65uy 0x76uy |]
更新:我修改了代码以显示十六进制输出。
如何在 F# 中创建可以加密字节数组的 xor 函数?我从 Github 那里得到这段代码,但它加密了一个字符串。
open System
let encrypt (word : string) =
let key = "KCQ"
[ 0..(word.Length - 1) ]
|> Seq.map (fun idx -> Convert.ToChar(Convert.ToInt32 word.[idx] ^^^ Convert.ToInt32 key.[idx % key.Length]))
|> String.Concat
[<EntryPoint>]
let main argv =
let encrypted = encrypt "IzzyDev"
printfn "Encrypted: %s" encrypted
let decrypted = encrypt encrypted
printfn "Decrypted: %s" decrypted
0
我如何修改此代码以使其加密字节数组而不是字符串?
我修改了您的示例以加密字节数组而不是字符串:
let toBytes (str : string) =
System.Text.Encoding.ASCII.GetBytes(str)
let encrypt (bytes : byte[]) =
let key = toBytes "KCQ"
[ 0..(bytes.Length - 1) ]
|> Seq.map (fun idx -> bytes.[idx] ^^^ key.[idx % key.Length])
|> Seq.toArray
let printBytes (bytes : byte[]) =
printf "[| "
for byte in bytes do
printf "0x%02xuy " byte
printfn "|]"
[<EntryPoint>]
let main argv =
let unencrypted = toBytes "IzzyDev"
printfn "Unencrypted:"
printBytes unencrypted
let encrypted = encrypt unencrypted
printfn "Encrypted:"
printBytes encrypted
let decrypted = encrypt encrypted
printfn "Decrypted:"
printBytes decrypted
0
输出:
Unencrypted:
[| 0x49uy 0x7auy 0x7auy 0x79uy 0x44uy 0x65uy 0x76uy |]
Encrypted:
[| 0x02uy 0x39uy 0x2buy 0x32uy 0x07uy 0x34uy 0x3duy |]
Decrypted:
[| 0x49uy 0x7auy 0x7auy 0x79uy 0x44uy 0x65uy 0x76uy |]
更新:我修改了代码以显示十六进制输出。