1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
|
unit SLTJWT;
interface
uses
System.SysUtils, System.Types, System.Hash;
type
TSLTJWT = class;
TSLTJWTClaimsStandard = class;
ESLTJWTError = class(Exception);
TSLTJWTAlgorithm = (jwaUnknown, jwaNone, jwaHS256, jwaHS384, jwaHS512);
TSLTJWTTokenType = (jttUnknown, jttJWT);
TSLTJWTDigestType = THashSHA2.TSHA2Version;
TSLTJWT = class(TObject)
private
FHeaderAlgorithm: TSLTJWTAlgorithm;
FHeaderTokenType: TSLTJWTTokenType;
FClaimsStandard: TSLTJWTClaimsStandard;
function ToJSONString(): string;
public
constructor Create();
destructor Destroy; override;
function BuildJSONStrings(out AHeader, APayload: string): Boolean;
function EncodeJSONStrings(const AHeader, APayload: string; out AEncodedPart: string): Boolean;
function SignJSONEncodedPart(const AEncodedPart: string; const AKey: string; AKeyBase64Encoded: Boolean; out AToken: string): Boolean;
function DigestSignJSON(const AToken: string; ADigestType: TSLTJWTDigestType; ABase64URLEncoded: Boolean; out ADigest: string; var ASalt: string): Boolean;
property HeaderAlgorithm: TSLTJWTAlgorithm read FHeaderAlgorithm write FHeaderAlgorithm;
property HeaderTokenType: TSLTJWTTokenType read FHeaderTokenType write FHeaderTokenType;
property ClaimsStandard: TSLTJWTClaimsStandard read FClaimsStandard;
public
class function GetSupportedAlgorithms(): TStringDynArray;
class function GetSupportedTokenTypes(): TStringDynArray;
class function GetDefaultAlgorithm(): string;
class function GetDefaultTokenType(): string;
class function GetAlgorithm(const ACode: string): TSLTJWTAlgorithm;
class function GetTokenType(const ACode: string): TSLTJWTTokenType;
end;
TSLTJWTClaimsStandard = class(TObject)
private
FIssuer: string;
FSubject: string;
FAudience: string;
FExpirationTime: TDateTime;
FNotBefore: TDateTime;
FIssuedAt: TDateTime;
FJWTID: string;
public
function ToJSONString(): string;
property Issuer: string read FIssuer write FIssuer;
property Subject: string read FSubject write FSubject;
property Audience: string read FAudience write FAudience;
property ExpirationTime: TDateTime read FExpirationTime write FExpirationTime;
property NotBefore: TDateTime read FNotBefore write FNotBefore;
property IssuedAt: TDateTime read FIssuedAt write FIssuedAt;
property JWTID: string read FJWTID write FJWTID;
end;
implementation
uses System.TypInfo, System.JSON, System.StrUtils, System.DateUtils, System.NetEncoding;
const
SLT_JWT_ALGORITHMS: array[TSLTJWTAlgorithm] of string = ('', 'None', 'HS256', 'HS384', 'HS512');
SLT_JWT_TOKEN_TYPES: array[TSLTJWTTokenType] of string = ('', 'JWT');
{ TSLTJWT }
// https://docwiki.embarcadero.com/RADStudio/Alexandria/en/What%27s_New : New TBase64URLEncoding encoding and TNetEncoding.Base64URL property
const
CompilerVersionAlexandria = 35.0;
CompilerVersionSeattle = 30.0;
{$IF CompilerVersion < CompilerVersionAlexandria}
type
TBase64URLEncoding = class(TBase64Encoding)
protected
function DoDecode(const Input: string): string; override;
function DoEncode(const Input: string): string; override;
function DoEncodeBytesToString(const Input: array of Byte): string; overload; override;
end;
{$IFEND}
//------------------------------------------------------------------------------
constructor TSLTJWT.Create();
begin
inherited Create();
FClaimsStandard := TSLTJWTClaimsStandard.Create();
end;
//------------------------------------------------------------------------------
destructor TSLTJWT.Destroy();
begin
FreeAndNil(FClaimsStandard);
inherited Destroy();
end;
//------------------------------------------------------------------------------
function TSLTJWT.BuildJSONStrings(out AHeader, APayload: string): Boolean;
begin
AHeader := ToJSONString();
APayload := FClaimsStandard.ToJSONString();
Result := True;
end;
//------------------------------------------------------------------------------
function TSLTJWT.EncodeJSONStrings(const AHeader, APayload: string; out AEncodedPart: string): Boolean;
begin
with TBase64URLEncoding.Create(0) do
try
AEncodedPart := Encode(AHeader) + '.' + Encode(APayload);
finally
Free();
end;
Result := True;
end;
//------------------------------------------------------------------------------
function TSLTJWT.SignJSONEncodedPart(const AEncodedPart: string; const AKey: string; AKeyBase64Encoded: Boolean; out AToken: string): Boolean;
type
TMapEntry = record
JWTAlgorithm: TSLTJWTAlgorithm;
SHA2Version: THashSHA2.TSHA2Version;
end;
const
SHA_TABLES: array[1..3] of TMapEntry =
(
(JWTAlgorithm: jwaHS256; SHA2Version: SHA256;),
(JWTAlgorithm: jwaHS384; SHA2Version: SHA384;),
(JWTAlgorithm: jwaHS512; SHA2Version: SHA512;)
);
function GetSHA2Version(): THashSHA2.TSHA2Version;
var
it: TMapEntry;
begin
for it in SHA_TABLES do
if it.JWTAlgorithm = FHeaderAlgorithm then
Exit(it.SHA2Version);
raise ESLTJWTError.Create('Invalid Algorithm for Sign');
end;
var
B: TBytes;
begin
if AKeyBase64Encoded then
B := System.Hash.THashSHA2.GetHMACAsBytes(AEncodedPart, TNetEncoding.Base64.Decode(AKey), GetSHA2Version())
else
B := System.Hash.THashSHA2.GetHMACAsBytes(AEncodedPart, AKey, GetSHA2Version());
with TBase64URLEncoding.Create(0) do
try
AToken := AEncodedPart + '.' + EncodeBytesToString(B);
finally
Free();
end;
Result := True;
end;
//------------------------------------------------------------------------------
function TSLTJWT.DigestSignJSON(const AToken: string; ADigestType: TSLTJWTDigestType; ABase64URLEncoded: Boolean; out ADigest: string; var ASalt: string): Boolean;
function GetSALT(): string;
var
B: TBytes;
begin
// 16 Bytes x 2 cela donne un 32 Bytes
B := TGUID.NewGuid().ToByteArray() + TGUID.NewGuid().ToByteArray();
// Encodage en Base64 augmente le volume de 32 à 43 Bytes (3 bytes deviennt 4 caractères)
with TBase64URLEncoding.Create(0) do
try
Result := Copy(EncodeBytesToString(B), 1, 32);
finally
Free();
end;
end;
begin
if ASalt = '' then
ASalt := GetSALT();
if ABase64URLEncoded then
begin
with TBase64URLEncoding.Create(0) do
try
ADigest := EncodeBytesToString(System.Hash.THashSHA2.GetHashBytes(ASalt + AToken, ADigestType));
finally
Free();
end;
end
else
ADigest := System.Hash.THashSHA2.GetHashString(ASalt + AToken, ADigestType);
Result := True;
end;
//------------------------------------------------------------------------------
function TSLTJWT.ToJSONString(): string;
begin
if FHeaderAlgorithm = jwaUnknown then
raise ESLTJWTError.Create('Unknown Algorithm');
if FHeaderTokenType = jttUnknown then
raise ESLTJWTError.Create('Unknown Token Type');
with TJSONObject.Create() do
try
AddPair(TJSONPair.Create('alg', TJSONString.Create(SLT_JWT_ALGORITHMS[FHeaderAlgorithm])));
AddPair(TJSONPair.Create('typ', TJSONString.Create(SLT_JWT_TOKEN_TYPES[FHeaderTokenType])));
Result := ToJSON();
finally
Free();
end;
end;
//------------------------------------------------------------------------------
class function TSLTJWT.GetDefaultAlgorithm(): string;
begin
Result := SLT_JWT_ALGORITHMS[jwaHS512];
end;
//------------------------------------------------------------------------------
class function TSLTJWT.GetDefaultTokenType(): string;
begin
Result := SLT_JWT_TOKEN_TYPES[jttJWT];
end;
//------------------------------------------------------------------------------
class function TSLTJWT.GetSupportedAlgorithms(): TStringDynArray;
var
I: TSLTJWTAlgorithm;
L: Integer;
begin
I := Succ(Low(SLT_JWT_ALGORITHMS));
L := Ord(High(SLT_JWT_ALGORITHMS)) - Ord(I) + 1;
SetLength(Result, L);
CopyArray(@Result[0], @SLT_JWT_ALGORITHMS[I], TypeInfo(string), L);
end;
//------------------------------------------------------------------------------
class function TSLTJWT.GetSupportedTokenTypes(): TStringDynArray;
var
I: TSLTJWTTokenType;
L: Integer;
begin
I := Succ(Low(SLT_JWT_TOKEN_TYPES));
L := Ord(High(SLT_JWT_TOKEN_TYPES)) - Ord(I) + 1;
SetLength(Result, L);
CopyArray(@Result[0], @SLT_JWT_TOKEN_TYPES[I], TypeInfo(string), L);
end;
//------------------------------------------------------------------------------
class function TSLTJWT.GetAlgorithm(const ACode: string): TSLTJWTAlgorithm;
var
I: Integer;
begin
if ACode <> '' then
begin
I := IndexStr(ACode, SLT_JWT_ALGORITHMS);
if (Ord(Low(TSLTJWTAlgorithm)) < I) and (I <= Ord(High(TSLTJWTAlgorithm))) then
Result := TSLTJWTAlgorithm(I)
else
raise ESLTJWTError.CreateFmt('Invalid Algorithm (%s)', [ACode]);
end
else
raise ESLTJWTError.Create('Empty Algorithm');
end;
//------------------------------------------------------------------------------
class function TSLTJWT.GetTokenType(const ACode: string): TSLTJWTTokenType;
var
I: Integer;
begin
if ACode <> '' then
begin
I := IndexStr(ACode, SLT_JWT_TOKEN_TYPES);
if (Ord(Low(TSLTJWTTokenType)) < I) and (I <= Ord(High(TSLTJWTTokenType))) then
Result := TSLTJWTTokenType(I)
else
raise ESLTJWTError.CreateFmt('Invalid Token Type (%s)', [ACode]);
end
else
raise ESLTJWTError.Create('Empty Token Type');
end;
{ TSLTJWTClaimsStandard }
//------------------------------------------------------------------------------
function TSLTJWTClaimsStandard.ToJSONString(): string;
begin
with TJSONObject.Create() do
try
if FIssuer <> '' then
AddPair(TJSONPair.Create('iss', TJSONString.Create(FIssuer)));
if FSubject <> '' then
AddPair(TJSONPair.Create('sub', TJSONString.Create(FSubject)));
if FAudience <> '' then
AddPair(TJSONPair.Create('aud', TJSONString.Create(FAudience)));
if FExpirationTime > 0 then
AddPair(TJSONPair.Create('exp', TJSONNumber.Create(DateTimeToUnix(FExpirationTime, False))));
if FNotBefore > 0 then
AddPair(TJSONPair.Create('nbf', TJSONNumber.Create(DateTimeToUnix(FNotBefore, False))));
if FIssuedAt > 0 then
AddPair(TJSONPair.Create('iat', TJSONNumber.Create(DateTimeToUnix(FIssuedAt, False))));
if FJWTID <> '' then
AddPair(TJSONPair.Create('jti', TJSONString.Create(FJWTID)));
Result := ToJSON();
finally
Free();
end;
end;
{ TBase64URLEncoding }
{$IF CompilerVersion < CompilerVersionAlexandria}
//------------------------------------------------------------------------------
function TBase64URLEncoding.DoDecode(const Input: string): string;
begin
Result := Input + StringOfChar('=', (4 - Length(Input) mod 4) mod 4);
Result := StringReplace(Result, '-', '+', [rfReplaceAll]);
Result := StringReplace(Result, '_', '/', [rfReplaceAll]);
Result := inherited DoEncode(Result);
end;
//------------------------------------------------------------------------------
function TBase64URLEncoding.DoEncode(const Input: string): string;
begin
Result := inherited DoEncode(Input);
Result := StringReplace(Result, '+', '-', [rfReplaceAll]);
Result := StringReplace(Result, '/', '_', [rfReplaceAll]);
Result := StringReplace(Result, '=', '', [rfReplaceAll]);
end;
//------------------------------------------------------------------------------
function TBase64URLEncoding.DoEncodeBytesToString(const Input: array of Byte): string;
begin
Result := inherited DoEncodeBytesToString(Input);
Result := StringReplace(Result, '+', '-', [rfReplaceAll]);
Result := StringReplace(Result, '/', '_', [rfReplaceAll]);
Result := StringReplace(Result, '=', '', [rfReplaceAll]);
end;
{$IFEND}
end. |
Partager