Release Date: 2025-03-03
Author: [tarek]
This major release brings robust RSA key handling, enhanced SHA-256 signing/verification, and a revamped Password module supporting both synchronous and asynchronous operations. We have also standardized error messages, enriched TypeScript definitions, and introduced additional security best practices.
If you’re upgrading from a previous version, check out the Migration Notes for essential changes.
-
Highlights
1.1 RSA Key Enhancements
1.2 SHA-256 Overhaul
1.3 Password Module Revamp
1.4 Refined Error Handling
1.5 TypeScript Improvements - Breaking Changes
- Migration Notes
-
Example Usage
4.1 Password Hashing
4.2 RSA Encryption (Async)
4.3 SHA-256 Sign & Verify - Contribute & Support
- License
-
Async RSA Key Generation
-
JWT.RSASync.GenrateKeys()
now relies on the non-blockinggenerateKeyPair
under the hood. - This improvement prevents event-loop blocking during 2048-bit RSA key creation in production apps.
-
-
Consistent PEM/DER Format
- No more
toString("hex")
for private keys. The library stores RSA keys in standard PEM format. - Fixes
DECODER routines::unsupported
errors when encrypting or decrypting with Node.js.
- No more
-
Unified RSA Encryption API
-
publicEncrypt
is used by default. If it fails, we gracefully fallback toprivateEncrypt
only for specialized use cases. - Clear error messages for invalid or unsupported keys.
-
-
Sign / Verify with Extended Options
-
JWT.SHA256.Sign
andJWT.SHA256.Verify
can now handle typical JWT-like fields:iat
,exp
,nbf
,iss
,sub
,aud
,jti
. - Built-in checks for
exp
(expiration) andnbf
(not before) automatically throw an error or returnError
if the token is expired or inactive.
-
-
Async Wrapper
-
JWT.SHA256Sync
(previouslySHA256Sync
) returns Promises instead of direct values, letting you integrate with async/await more easily.
-
-
Improved Defaults
- Default
encoding
is"hex"
, but you can switch to"base64"
,"base64url"
, or"latin1"
to meet your project’s requirements.
- Default
-
Synchronous (
Hash.Password
)-
Hash: One-step password hashing that combines
bcrypt
with optional encryption logic. -
Match: Verifies a hashed password. Returns a boolean or an
Error
if something goes wrong.
-
Hash: One-step password hashing that combines
-
Asynchronous (
Hash.PasswordSync
)-
Hash: Returns a
Promise<string | void>
, ideal for non-blocking environments. -
Match: Returns a
Promise<boolean | Error>
for streamlined error handling.
-
Hash: Returns a
-
Clearer Error Handling
- Distinguishes between invalid keys, short passwords, and mismatch scenarios.
- Synchronous usage remains backward-compatible, though async is recommended for production-scale apps.
-
Unified Error Format
- All library functions now either throw or return a consistent
Error
object with standardized messages. -
erroHandel
has been renamed toerrorHandle
for clarity.
- All library functions now either throw or return a consistent
-
Enhanced Logging
- If you catch an error, you’ll see a uniform structure, making it simpler to log or display in UIs.
- Optional custom error classes (e.g.,
TokenExpiredError
) can be integrated in future expansions.
-
Class Fields
- Public/Private static fields are declared using official TypeScript syntax, ensuring better IDE intellisense.
-
Interfaces
-
Sha256SignOptions
&Sha256DecryptOptions
extended for additional JWT-like fields (iss
,aud
,sub
,nbf
).
-
-
Manual Testing & Jest
- Provided
manual-test.ts
for quick local checks without a full test framework. - Updated
jest.config
forts-jest
usage, so you can run advanced test suites if needed.
- Provided
-
Private Key Format
- Private keys are now PEM-based, not hex. If your application stored hex-encoded keys, you must convert them back to PEM.
-
erroHandel
→errorHandle
- All references to the old
erroHandel
function have been replaced. Update your calls accordingly if you used that function name.
- All references to the old
-
New Default Encodings
- We strongly recommend using
"hex"
or"base64"
. If you previously forced"binary"
, confirm your tokens or hashed values still parse correctly.
- We strongly recommend using
-
Signature Checking
-
JWT.SHA256.Verify
re-computes the signature using the token’s last segment forencoding
. Ensure your tokens or code references the correct encoding in the final step.
-
-
PEM Keys
- Remove
.toString("hex")
calls. Store your private/public keys as standard PEM strings (with-----BEGIN RSA PRIVATE KEY-----
blocks).
- Remove
-
Async Patterns
- Switch from synchronous to asynchronous functions (e.g.,
Hash.PasswordSync
) if you want non-blocking password hashing in high-traffic apps.
- Switch from synchronous to asynchronous functions (e.g.,
-
Error Handling
- Replace any usage of
erroHandel
witherrorHandle
. - Check for new error messages and codes (e.g., “Token expired”, “Token not active yet”).
- Replace any usage of
-
Testing
- Run
manual-test.ts
to ensure your environment is set up to handle class fields, TypeScript, and Node.js crypto. - If you use Jest, confirm that
preset: 'ts-jest'
or Babel is configured properly.
- Run
import { Hash } from "addvansed-hash";
// Synchronous approach
const hashed = Hash.Password.Hash("myPassword", "myKey");
if (typeof hashed === "string") {
const match = Hash.Password.Match(hashed, "myPassword", "myKey");
console.log("Password match result:", match);
}
// Async approach
(async () => {
const hashedAsync = await Hash.PasswordSync.Hash("myPassword", "myKey");
if (typeof hashedAsync === "string") {
const matchAsync = await Hash.PasswordSync.Match(hashedAsync, "myPassword", "myKey");
console.log("Password match async result:", matchAsync);
}
})();
import { JWT } from "addvansed-hash";
(async () => {
const keys = await JWT.RSASync.GenrateKeys();
if (keys) {
const ciphertext = await JWT.RSASync.Encrypt("Hello RSA!", keys.publicKey);
console.log("Encrypted text:", ciphertext);
const plaintext = await JWT.RSASync.Decrypt(ciphertext, keys.privateKey);
console.log("Decrypted text:", plaintext);
}
})();
import { JWT } from "addvansed-hash";
const secret = "mySecretKey";
const token = JWT.SHA256.Sign({ userId: 123 }, secret, { expiresIn: 3600, iat: true });
console.log("Generated token:", token);
if (typeof token === "string") {
const verification = JWT.SHA256.Verify(token, secret, {});
if (verification instanceof Error) {
console.error("Token verification failed:", verification.message);
} else {
console.log("Verified payload:", verification);
}
}
- Issues / Feature Requests: File them in GitHub Issues.
- Discussions / Q&A: Post your questions or ideas on GitHub Discussions.
- Pull Requests: Always welcome—just follow our CONTRIBUTING.md guidelines.
- Security Reports: If you find a vulnerability, please contact us privately before disclosing publicly.
Distributed under the MIT License—you are free to use, modify, and distribute. See the LICENSE file for details.
Enjoy the “addvansed” level of security and performance!
We look forward to your feedback and contributions to keep addvansed-hash moving forward.