In this short tip, I will show you how to encrypt data with AES-256 in UE4.
The code will be written in C++ but can be used later in blueprints.
First thing what you need to do is to create a class, derived from UBlueprintFunctionLibrary.
Then add two methods to the header:
UFUNCTION(BlueprintCallable, Category = "AES256")
static FString Encrypt(FString InputString, FString Key);
UFUNCTION(BlueprintCallable, Category = "AES256")
static FString Decrypt(FString InputString, FString Key);
After that implement those methods:
FString UChangeToYourBlueprintFunctionLibraryName::Encrypt(FString InputString, FString Key)
{
// Check inputs
if (InputString.IsEmpty()) return ""; //empty string? do nothing
if (Key.IsEmpty()) return "";
// To split correctly final result of decryption from trash symbols
FString SplitSymbol = "EL@$@!";
InputString.Append(SplitSymbol);
// We need at least 32 symbols key
Key = FMD5::HashAnsiString(*Key);
TCHAR *KeyTChar = Key.GetCharArray().GetData();
ANSICHAR *KeyAnsi = (ANSICHAR*)TCHAR_TO_ANSI(KeyTChar);
// Calculate blob size and create blob
uint8* Blob;
uint32 Size;
Size = InputString.Len();
Size = Size + (FAES::AESBlockSize - (Size % FAES::AESBlockSize));
Blob = new uint8[Size];
// Convert string to bytes and encrypt
if(StringToBytes(InputString, Blob, Size)) {
FAES::EncryptData(Blob, Size, KeyAnsi);
InputString = FString::FromHexBlob(Blob, Size);
delete Blob;
return InputString;
}
delete Blob;
return "";
}
FString UChangeToYourBlueprintFunctionLibraryName::Decrypt(FString InputString, FString Key)
{
// Check inputs
if (InputString.IsEmpty()) return "";
if (Key.IsEmpty()) return "";
// To split correctly final result of decryption from trash symbols
FString SplitSymbol = "EL@$@!";
// We need at least 32 symbols key
Key = FMD5::HashAnsiString(*Key);
TCHAR *KeyTChar = Key.GetCharArray().GetData();
ANSICHAR *KeyAnsi = (ANSICHAR*)TCHAR_TO_ANSI(KeyTChar);
// Calculate blob size and create blob
uint8* Blob;
uint32 Size;
Size = InputString.Len();
Size = Size + (FAES::AESBlockSize - (Size % FAES::AESBlockSize));
Blob = new uint8[Size];
// Convert string to bytes and decrypt
if (FString::ToHexBlob(InputString, Blob, Size)) {
FAES::DecryptData(Blob, Size, KeyAnsi);
InputString = BytesToString(Blob, Size);
// Split required data from trash
FString LeftData;
FString RightData;
InputString.Split(SplitSymbol, &LeftData, &RightData, ESearchCase::CaseSensitive, ESearchDir::FromStart);
InputString = LeftData;
delete Blob;
return InputString;
}
delete Blob;
return "";
}
Don’t forget to add proper include headers:
#include "Runtime/Core/Public/Misc/AES.h"
#include "Runtime/Core/Public/Misc/SecureHash.h"
#include "Runtime/Core/Public/Misc/Base64.h"
Next, compile the project and that’s all. You can use those methods to encrypt/decrypt strings with the specified password. It’s possible to adapt those methods to work with other input parameters (like custom structs, bytes or integers).