Last active
June 11, 2018 07:48
-
-
Save st0326s/ad134493aa29123037a2995121be99b8 to your computer and use it in GitHub Desktop.
Unity C#で暗号化・復号化 メモ ref: http://qiita.com/satotin/items/6e0dc0a90312c5d474df
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Text; | |
using System.Security.Cryptography; | |
namespace Musashi.WebApi_v1.Utility | |
{ | |
/// <summary> | |
/// 暗号化・複合化を行う | |
/// </summary> | |
public static class Crypt | |
{ | |
private static AesCryptoServiceProvider GetCryptInstance() | |
{ | |
// AES暗号化サービスプロバイダ | |
AesCryptoServiceProvider aes = new AesCryptoServiceProvider(); | |
aes.BlockSize = 128; | |
aes.KeySize = 256; | |
aes.IV = Encoding.UTF8.GetBytes(任意の文字列); | |
aes.Key = Encoding.UTF8.GetBytes(任意の文字列); | |
aes.Mode = CipherMode.CBC; | |
aes.Padding = PaddingMode.PKCS7; | |
return aes; | |
} | |
// ラムダ式にしてみる | |
public static byte[] CryptProcess(byte[] src, bool isEncrypt) | |
{ | |
// AES暗号化サービスプロバイダ | |
AesCryptoServiceProvider aes = GetCryptInstance(); | |
byte[] isOK = ((Func<byte[]>)(() => {using (ICryptoTransform encrypt = aes.CreateEncryptor()){return encrypt.TransformFinalBlock(src, 0, src.Length);}}))(); | |
// フラグによって暗号、復号の処理を分ける。 | |
return isEncrypt == true ? | |
((Func<byte[]>)(() => { using (ICryptoTransform encrypt = aes.CreateEncryptor()) { return encrypt.TransformFinalBlock(src, 0, src.Length); } }))() | |
: | |
((Func<byte[]>)(() => { using (ICryptoTransform decrypt = aes.CreateDecryptor()) { return decrypt.TransformFinalBlock(src, 0, src.Length); } }))(); | |
} | |
/// <summary> | |
/// AESで暗号化 | |
/// </summary> | |
public static byte[] Encrypt(byte[] src) | |
{ | |
// AES暗号化サービスプロバイダ | |
AesCryptoServiceProvider aes = GetCryptInstance(); | |
// 暗号化する | |
using (ICryptoTransform encrypt = aes.CreateEncryptor()) | |
{ | |
return encrypt.TransformFinalBlock(src, 0, src.Length); | |
} | |
} | |
/// <summary> | |
/// 文字列をAESで復号化 | |
/// </summary> | |
public static byte[] Decrypt(byte[] src) | |
{ | |
// AES暗号化サービスプロバイダ | |
AesCryptoServiceProvider aes = GetCryptInstance(); | |
// 複号化する | |
using (ICryptoTransform decrypt = aes.CreateDecryptor()) | |
{ | |
return decrypt.TransformFinalBlock(src, 0, src.Length); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment