Convert code from JS to C# 'use strict'; const crypto = require('crypto'); const…
- User
Convert code from JS to C#
'use strict'; const crypto = require('crypto'); const IV_LENGTH = 16; const tokenBody = {
"access_token": "", "iat": Date.now() / 1000, "exp": (Date.now() / 1000) + (60 * 60), "subject": "login_with_eljour", "payload":{"is_child":0,"ip":"123.123.123,123"}, } const serviceKey = "36dc4fc036dc4fc036dc4fc09635c998af336dc36dc4fc053c126f34ef4d62ecaab3eb0"; const encrypted = encrypt(JSON.stringify(tokenBody), serviceKey); console.log('encrypted: ' + encrypted); console.log('decrypted: ' + decrypt(encrypted, serviceKey)); function encrypt(text, key) {
const [encryptKey, signKey] = prepareKeys(key); let iv = crypto.randomBytes(IV_LENGTH); let cipher = crypto.createCipheriv('aes-256-cbc', encryptKey, iv); let encrypted = cipher.update(text); encrypted = Buffer.concat([encrypted, cipher.final()]); encrypted = Buffer.concat([iv, encrypted]); let signature = hmac(encrypted, signKey); return Buffer.concat([signature, encrypted]).toString('base64'); }
function decrypt(text, key) { const [encryptKey, signKey] = prepareKeys(key); text = Buffer.from(text, 'base64'); let signature = text.slice(0, 32); let ciphertext = text.slice(32); if (Buffer.compare(hmac(ciphertext, signKey), signature)) { throw new Error('Signature does not match'); } let iv = ciphertext.slice(0, IV_LENGTH); let encryptedText = ciphertext.slice(IV_LENGTH); let decipher = crypto.createDecipheriv('aes-256-cbc', encryptKey, iv); let decrypted = decipher.update(encryptedText); decrypted = Buffer.concat([decrypted, decipher.final()]); return decrypted.toString('utf-8'); } function prepareKeys(key) { const hash = crypto.createHash('sha512'); hash.update(key); const hashed = hash.digest(); return [ hashed.slice(0, 32), hashed.slice(32), ]; } function hmac(data, key) { return crypto.createHmac('sha256', key) .update(data) .digest(); } module.exports = { decrypt, encrypt };
- Assistant