Skip to content
This repository has been archived by the owner on Mar 28, 2024. It is now read-only.

Commit

Permalink
feat(crypto): prefix option
Browse files Browse the repository at this point in the history
  • Loading branch information
alimd committed Nov 29, 2023
1 parent 9d718b2 commit 6be5c90
Show file tree
Hide file tree
Showing 9 changed files with 30 additions and 24 deletions.
1 change: 1 addition & 0 deletions demo/crypto/benchmark.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ if (process.env.NODE_ENV !== 'production') {
}

const tokenGenerator = new AlwatrTokenGenerator({
prefix: 't_',
secret: 'my-very-secret-key',
duration: null,
algorithm: 'md5',
Expand Down
1 change: 1 addition & 0 deletions demo/crypto/hash.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {AlwatrHashGenerator} from '@alwatr/crypto';

const hashGenerator = new AlwatrHashGenerator({
prefix: 'h_',
algorithm: 'sha1',
encoding: 'base64url',
crcLength: 8,
Expand Down
4 changes: 3 additions & 1 deletion demo/crypto/rand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,7 @@ import {AlwatrHashGenerator, secretGeneratorPreConfig} from '@alwatr/crypto';
const hashGenerator = new AlwatrHashGenerator(secretGeneratorPreConfig);

for (let i = 0; i <= 10; i++) {
console.log('hash: %s', hashGenerator.generateRandomSelfValidate());
const hash = hashGenerator.generateRandomSelfValidate();
const validate = hashGenerator.verifySelfValidate(hash);
console.log('hash: %s, validate: %s', hash, validate);
}
1 change: 1 addition & 0 deletions demo/crypto/token.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {createLogger} from '@alwatr/logger';
const logger = createLogger('token/demo', true);

const tokenGenerator = new AlwatrTokenGenerator({
prefix: 't_',
secret: 'my-very-secret-key',
duration: '2s',
algorithm: 'sha512',
Expand Down
27 changes: 12 additions & 15 deletions demo/crypto/user.ts
Original file line number Diff line number Diff line change
@@ -1,42 +1,39 @@
import {AlwatrUserGenerator} from '@alwatr/crypto';
import {AlwatrUserGenerator, userIdGeneratorPreConfig, userTokenGeneratorPreConfig} from '@alwatr/crypto';
import {createLogger} from '@alwatr/logger';
import {delay} from '@alwatr/util';

import type {User} from '@alwatr/type';

const logger = createLogger('crypto/user', true);

const userFactory = new AlwatrUserGenerator({
userId: {
algorithm: 'sha1',
encoding: 'base64url',
crcLength: 4,
},
const newLocal = 'my-very-secret-key';
const userGenerator = new AlwatrUserGenerator({
userId: userIdGeneratorPreConfig,
token: {
secret: 'my-very-secret-key',
...userTokenGeneratorPreConfig,
secret: newLocal,
duration: '2s',
algorithm: 'sha512',
encoding: 'base64url',
},
});

const user: User = {
id: userFactory.generateUserId(),
id: userGenerator.generateUserId(),
country: 'iran',
fullName: 'امیرمحمد نجفی',
gender: 'male',
lpe: 1,
phoneNumber: 989151234567,
};

const userIdValidation = userFactory.verifyUserId(user.id);
logger.logOther?.('user id validation:', userIdValidation);
logger.logProperty?.('user', user);

logger.logOther?.('verifyUserId:', userGenerator.verifyUserId(user.id));

const userToken = userFactory.generateToken([user.id, user.lpe]);
const userToken = userGenerator.generateToken([user.id, user.lpe]);
logger.logOther?.('user token:', userToken);

const userTokenValidation = (): void => {
const tokenValidationStatus = userFactory.verifyToken([user.id, user.lpe], userToken);
const tokenValidationStatus = userGenerator.verifyToken([user.id, user.lpe], userToken);
logger.logOther?.('user token validation status:', tokenValidationStatus);
};

Expand Down
10 changes: 5 additions & 5 deletions packages/crypto/src/hash.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ export class AlwatrHashGenerator {
* ```
*/
generate(data: BinaryLike): string {
return createHash(this.config.algorithm).update(data).digest(this.config.encoding);
return this.config.prefix + createHash(this.config.algorithm).update(data).digest(this.config.encoding);
}

/**
Expand All @@ -56,7 +56,7 @@ export class AlwatrHashGenerator {
*/
generateCrc(data: BinaryLike): string {
const crc = createHash('sha1').update(data).digest(this.config.encoding);
return this.config.crcLength == null || this.config.crcLength < 1 ? crc : crc.substring(0, this.config.crcLength);
return this.config.crcLength == null || this.config.crcLength < 1 ? crc : crc.slice(0, this.config.crcLength);
}

/**
Expand Down Expand Up @@ -104,10 +104,10 @@ export class AlwatrHashGenerator {
verifySelfValidate(hash: string): boolean {
const gapPos =
this.config.crcLength == null || this.config.crcLength < 1
? hash.length / 2
? hash.length - (hash.length - this.config.prefix.length) / 2
: hash.length - this.config.crcLength;
const mainHash = hash.substring(0, gapPos);
const crcHash = hash.substring(gapPos);
const mainHash = hash.slice(0, gapPos);
const crcHash = hash.slice(gapPos);
return crcHash === this.generateCrc(mainHash);
}
}
2 changes: 1 addition & 1 deletion packages/crypto/src/token.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ export class AlwatrTokenGenerator {
* @returns The generated cryptographic token.
*/
protected _generate(data: string, epoch: number): string {
return createHmac(this.config.algorithm, data)
return this.config.prefix + createHmac(this.config.algorithm, data)
.update(data + epoch)
.digest(this.config.encoding);
}
Expand Down
4 changes: 4 additions & 0 deletions packages/crypto/src/type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ export type TokenStatus = 'valid' | 'invalid' | 'expired';
export type HashStatus = 'valid' | 'invalid';

export interface TokenGeneratorConfig {
prefix: string;

/**
* Secret string data to generate token.
*/
Expand All @@ -31,6 +33,8 @@ export interface TokenGeneratorConfig {
}

export interface HashGeneratorConfig {
prefix: string;

/**
* OpenSSl digest algorithm.
*/
Expand Down
4 changes: 2 additions & 2 deletions packages/crypto/src/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export class AlwatrUserGenerator {
* ```
*/
generateUserId(): string {
return 'U' + this._hashGenerator.generateRandomSelfValidate();
return this._hashGenerator.generateRandomSelfValidate();
}

/**
Expand All @@ -47,7 +47,7 @@ export class AlwatrUserGenerator {
* ```
*/
verifyUserId(userId: string): boolean {
return this._hashGenerator.verifySelfValidate(userId.substring(1));
return this._hashGenerator.verifySelfValidate(userId);
}

/**
Expand Down

0 comments on commit 6be5c90

Please sign in to comment.