crypto#createHash JavaScript Examples

The following examples show how to use crypto#createHash. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: signoutkc.js    From RC4Community with Apache License 2.0 6 votes vote down vote up
export default function signoutkc(req,res){
    const [cookieCsrfToken,cookieCsrfTokenHash] =  req.cookies['next-auth.csrf-token'].split('|');
    const expectedCsrfTokenHash = createHash("sha256")
      .update(`${cookieCsrfToken}${process.env.NEXTAUTH_SECRET}`)
      .digest("hex");
    const redirectUri = req.query.callbackUrl? encodeURIComponent(req.query.callbackUrl) : process.env.NEXTAUTH_URL;
    if(cookieCsrfTokenHash === expectedCsrfTokenHash && cookieCsrfToken === req.query.token){
        res.redirect(`${process.env.KEYCLOAK_ISSUER}/protocol/openid-connect/logout?redirect_uri=${redirectUri}`);
    } else {
        res.statusCode = 401;
        res.end();
    }
}
Example #2
Source File: headers.js    From ucompress with ISC License 6 votes vote down vote up
getHash = source => new Promise(res => {
  const hash = createHash('sha1');
  const input = createReadStream(source);
  input.on('readable', () => {
    const data = input.read();
    if (data)
      hash.update(data, 'utf-8');
    else
      res(hash.digest('base64'));
  });
})
Example #3
Source File: crypto.js    From lx-music-mobile with Apache License 2.0 6 votes vote down vote up
eapi = (url, object) => {
  const text = typeof object === 'object' ? JSON.stringify(object) : object
  const message = `nobody${url}use${text}md5forencrypt`
  const digest = createHash('md5').update(message).digest('hex')
  const data = `${url}-36cd479b6b5-${text}-36cd479b6b5-${digest}`
  return {
    params: aesEncrypt(Buffer.from(data), 'aes-128-ecb', eapiKey, '').toString('hex').toUpperCase(),
  }
}
Example #4
Source File: http.js    From habitat-rollup with The Unlicense 5 votes vote down vote up
function onRequest (req, resp) {
  let path = url.parse(req.url).pathname;
  const remoteAddr = req.socket.remoteAddress;

  console.log(remoteAddr, req.method, path);

  if (path.indexOf('..') !== -1) {
    resp.writeHead(500);
    resp.end();
    return;
  }

  path = path.slice(1) || 'index.html';

  let buf;
  if (fs.existsSync(path)) {
    try {
      buf = fs.readFileSync(path);
    } catch (e) {
      if (e.code === 'EISDIR') {
        if (!path.endsWith('/')) {
          resp.writeHead(308, { location: `http://${req.headers['host']}/${path}/` });
          resp.end();
          return;
        }
        path += '/index.html';
      } else {
        resp.writeHead(500);
        resp.end('500');
        return;
      }
    }

    try {
      buf = buf || fs.readFileSync(path);
    } catch (e) {
      resp.writeHead(404);
      resp.end('404');
      return;
    }

    const eTag = createHash('sha1').update(buf).digest('hex');
    const ifNoneMatch = req.headers['if-none-match'] || '';
    if (ifNoneMatch === eTag) {
      // not modified
      resp.writeHead(304);
      resp.end();
      return;
    }

    resp.setHeader('etag', eTag);

    if (path.endsWith('.js')) {
      resp.setHeader('content-type', 'application/javascript');
    } else if (path.endsWith('.svg')) {
      resp.setHeader('content-type', 'image/svg+xml');
    }

    resp.end(buf);
    return;
  }

  resp.writeHead(404);
  resp.end('404');
}
Example #5
Source File: exp-ceksn.js    From HinataMd with GNU General Public License v3.0 5 votes vote down vote up
handler = async function (m, { conn, text, usedPrefix }) {
  let sn = createHash('md5').update(m.sender).digest('hex')

m.reply(`*? SN:* ${sn}`)
}
Example #6
Source File: exp-unreg.js    From HinataMd with GNU General Public License v3.0 5 votes vote down vote up
handler = async function (m, { args }) {
  if (!args[0]) throw 'Serial Number kosong'
  let user = global.db.data.users[m.sender]
  let sn = createHash('md5').update(m.sender).digest('hex')
  if (args[0] !== sn) throw 'Serial Number salah'
  user.registered = false
  m.reply('```Succes Unreg !```')
}
Example #7
Source File: common.js    From Pixiv_bot with MIT License 5 votes vote down vote up
export function generate_token(user_id, time = +new Date()) {
    return createHash('sha1').update(`${config.tg.salt}${user_id}${time}`).digest('hex').toString()
}
Example #8
Source File: lnurl.js    From stacker.news with MIT License 5 votes vote down vote up
export function lnurlPayDescriptionHash (data) {
  return createHash('sha256').update(data).digest('hex')
}
Example #9
Source File: exp-daftar.js    From HinataMd with GNU General Public License v3.0 4 votes vote down vote up
handler = async function (m, { text, usedPrefix, command }) {
	function pickRandom(list) {
  return list[Math.floor(Math.random() * list.length)]
}
	let namae = conn.getName(m.sender)
	const sections = [
	{
	title: "Select Your Age Here !",
	rows: [
	    {title: "Random Years", rowId: '.daftar ' + namae + '.' + pickRandom(['30','29','28','27','26','25','24','23','22','21','20','19','18','17','16','15','14','13','12','11','10','9'])}
	]
    },
    {
	title: "O L D",
	rows: [
	    {title: "30 Years", rowId: '.daftar ' + namae + '.30 '},
	    {title: "29 Years", rowId: '.daftar ' + namae + '.29 '},
	    {title: "28 Years", rowId: '.daftar ' + namae + '.28 '},
	{title: "27 Years", rowId: '.daftar ' + namae + '.27 '},
	{title: "26 Years", rowId: '.daftar ' + namae + '.26 '},
	{title: "25 Years", rowId: '.daftar ' + namae + '.25 '},
	{title: "24 Years", rowId: '.daftar ' + namae + '.24 '},
	{title: "23 Years", rowId: '.daftar ' + namae + '.23 '},
	{title: "22 Years", rowId: '.daftar ' + namae + '.22 '},
	{title: "21 Years", rowId: '.daftar ' + namae + '.21 '}
	]
    },
    {
	title: "Y O U N G",
	rows: [
	    {title: "20 Years", rowId: '.daftar ' + namae + '.20 '},
	    {title: "19 Years", rowId: '.daftar ' + namae + '.19 '},
	    {title: "18 Years", rowId: '.daftar ' + namae + '.18 '},
	{title: "17 Years", rowId: '.daftar ' + namae + '.17 '},
	{title: "16 Years", rowId: '.daftar ' + namae + '.16 '},
	{title: "15 Years", rowId: '.daftar ' + namae + '.15 '},
	{title: "14 Years", rowId: '.daftar ' + namae + '.14 '},
	{title: "13 Years", rowId: '.daftar ' + namae + '.13 '},
	{title: "12 Years", rowId: '.daftar ' + namae + '.12 '},
	{title: "11 Years", rowId: '.daftar ' + namae + '.11 '},
	{title: "10 Years", rowId: '.daftar ' + namae + '.10 '},
	{title: "9 Years", rowId: '.daftar ' + namae + '.9 '}
	]
    },
]

const listMessage = {
  text: `│›Please select your age at the bottom button...`,
  footer: `┗ *ʏᴏᴜʀ ɴᴀᴍᴇ:* ${conn.getName(m.sender)}\n<❔> Want a costume name? type *${usedPrefix + command} yourname.age*`,
  title: "▢- - - - - ʀᴇɢɪsᴛᴇʀ - - - - -",
  buttonText: "Click Here !",
  sections
}

  let user = global.db.data.users[m.sender]
  if (user.registered === true) throw `[?] Kamu sudah terdaftar\nMau daftar ulang? *${usedPrefix}unreg <SERIAL NUMBER>*`
  if (!Reg.test(text)) return conn.sendMessage(m.chat, listMessage, { quoted: m })
  let [_, name, splitter, age] = text.match(Reg)
  if (!name) throw 'Nama tidak boleh kosong (Alphanumeric)'
  if (!age) throw 'Umur tidak boleh kosong (Angka)'
  age = parseInt(age)
  if (age > 30) throw 'WOI TUA (。-`ω´-)'
  if (age < 5) throw 'Halah dasar bocil'
  user.name = name.trim()
  user.age = age
  user.regTime = + new Date
  user.registered = true
  let sn = createHash('md5').update(m.sender).digest('hex')
  let who = m.mentionedJid && m.mentionedJid[0] ? m.mentionedJid[0] : m.quoted ? m.quoted.sender : m.fromMe ? conn.user.jid : m.sender
  let mim_ = ["application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/zip","application/pdf"]
let ngelink_ = ["https://www.youtube.com","https://www.instagram.com","http://facebook.com"]

  let cap = `
┏─• *ᴜsᴇʀs*
│▸ *sᴛᴀᴛᴜs:* ☑️ sᴜᴄᴄᴇssғᴜʟ
│▸ *ɴᴀᴍᴇ:* ${name}
│▸ *ᴀɢᴇ:* ${age} ʏᴇᴀʀs
│▸ *sɴ:* ${sn}
┗────···

ᴅᴀᴛᴀ ᴜsᴇʀ ʏᴀɴɢ ᴛᴇʀsɪᴍᴘᴀɴ ᴅɪᴅᴀᴛᴀʙᴀsᴇ ʙᴏᴛ, ᴅɪᴊᴀᴍɪɴ ᴀᴍᴀɴ ᴛᴀɴᴘᴀ ᴛᴇʀsʜᴀʀᴇ (. ❛ ᴗ ❛.)
`
  let buttonMessage= {
'document':{'url':gcwangsaf},
'mimetype':mim_.getRandom(),
'fileName':'- - - - - ʀᴇɢɪsᴛᴇʀ - - - - -',
'fileLength':fsizedoc,
'pageCount':fpagedoc,
'contextInfo':{
'forwardingScore':555,
'isForwarded':true,
'externalAdReply':{
'mediaUrl':ngelink_.getRandom(),
'mediaType':2,
'previewType':'pdf',
'title':author,
'body':bottime,
'thumbnail':await(await fetch(thumbnailUrl.getRandom())).buffer(),
'sourceUrl':gcwangsaf}},
'caption':cap,
'footer':wm,
'buttons':[
{'buttonId':'.menu','buttonText':{'displayText':'ᴍᴇɴᴜ'},'type':1},
{'buttonId':'.donasi','buttonText':{'displayText':'ᴅᴏɴᴀsɪ'},'type':1}
],
'headerType':6}
    await conn.sendMessage(m.chat,buttonMessage, { quoted:m})
}
Example #10
Source File: K8sUtils.js    From HandyHost with GNU Lesser General Public License v2.1 4 votes vote down vote up
createUbuntuISO(devicePath,pw,socketIONamespaces){
		return new Promise((resolve,reject)=>{
			this.generateSSHKey().then(()=>{
				//done
				this.getLocalIP().then((ip)=>{
					this.getRandomPW().then((randomPW)=>{
						const authToken = createHash('sha256').update( (Math.random() * ( new Date().getTime() )).toString() ).digest('hex');
						console.log('created auth token',authToken);
						fs.writeFileSync(process.env.HOME+'/.HandyHost/aktData/usbAuthToken',authToken.trim(),'utf8');
						const ssh_pub_key = fs.readFileSync(process.env.HOME+'/.ssh/handyhost.pub','utf8');
						const cloudInitTemplate = fs.readFileSync('./aktAPI/ubuntu-cloud-config-x86','utf8');
						
						let cloudInitOutput = cloudInitTemplate.replace(/__SSH_PUB_KEY__/g,ssh_pub_key.trim());
						cloudInitOutput = cloudInitOutput.replace(/__HOST_IP__/g,ip.trim());
						cloudInitOutput = cloudInitOutput.replace(/__USB_AUTH_TOKEN__/g,authToken.trim());
						cloudInitOutput = cloudInitOutput.replace(/__PASSWORD__/g,randomPW.trim());
						//cloudInitOutput = cloudInitOutput.replace(/__SSH_PUB_KEY__/g,ssh_pub_key);
						//3. write the config
						const generatorPath = process.env.HOME+'/.HandyHost/aktData/ubuntu-autoinstall-generator';

						fs.writeFileSync(generatorPath+'/user-data',cloudInitOutput,'utf8');
						//ok now to generate the ISO...
						console.log('device path',devicePath);
						let command = './aktAPI/generateUbuntuAutoinstallerISO.sh';
						if(process.platform == 'darwin'){
							command = './aktAPI/generateUbuntuAutoinstallerISO_MAC.sh';
						}
						let output = '';
						let errs = '';
						const autogen = spawn(command,[],{env:process.env,cwd:process.env.PWD});
						autogen.stdout.on('data',d=>{
							console.log('autogen stdout output: ',d.toString());
							Object.keys(socketIONamespaces).map(serverName=>{
								socketIONamespaces[serverName].namespace.to('akt').emit('flashUSBStatus',d.toString());
							})
							output += d.toString();
						})
						autogen.stderr.on('data',d=>{
							//ofc it dumps everything to stderr...
							console.log('autogen stderr output: ',d.toString());
							Object.keys(socketIONamespaces).map(serverName=>{
								socketIONamespaces[serverName].namespace.to('akt').emit('flashUSBStatus',d.toString());
							})
							errs += d.toString();
						})
						autogen.on('close',()=>{
							if(fs.existsSync(generatorPath+'/ubuntu-autoinstaller.iso')){
								//ok it wrote it then, lets continue
								const chunkSize = process.platform == 'darwin' ? '4m' : '4M';
								console.log('device path',devicePath,generatorPath);
								
								/*if(process.platform == 'darwin'){
									this.createUbuntuISOMAC(devicePath,pw,chunkSize,resolve,reject);
									return;
								}
								else{
									this.createUbuntuISOLinux(devicePath,pw,chunkSize,resolve,reject);
									return;
								}*/
								if(process.platform == 'darwin'){
									this.spawnCreateUbuntuISOMAC(devicePath,pw,chunkSize,resolve,reject,socketIONamespaces);
								}
								else{
									this.spawnCreateUbuntuISO(devicePath,pw,chunkSize,resolve,reject,socketIONamespaces);
								}
								
								return;
								
								
								
							}
							else{
								resolve({error:errs})
							}
							
						})
					
					}).catch(error=>{
						resolve({error:error})
					})
					
				}).catch(error=>{
					resolve({error:error})
				})
				
			}).catch(error=>{
				resolve({error:error})
			})
		})
	}
Example #11
Source File: generate.js    From dls-icons with MIT License 4 votes vote down vote up
async function normalizeSVG(content, file) {
  const shasum = createHash('sha1')
  shasum.update(content)
  const id = shasum.digest('hex').substring(0, 5)

  let { error, data } = await optimize(content, getSVGOConfig({ id }))
  if (error) {
    console.error(file, error)
    return
  }

  let el = await parse(data)
  console.log(`Normalizing ${file}...`)
  let { attributes } = el
  let { width, height, viewBox } = attributes

  if (!viewBox && !(width && height)) {
    console.error(file, `doesn't contain a valid size declaration.`)
    console.error(width, height, viewBox)
  } else if (viewBox) {
    // has viewBox, override width/height
    ;[, width, height] = (viewBox.match(/0 0 (\d+) (\d+)/) || []).map((size) =>
      parseInt(size, 10)
    )
  } else {
    // no viewBox, use width/height
    attributes.viewBox = `0 0 ${width} ${height}`
  }

  walkElement(el, {
    enter(node) {
      let { attributes } = node

      delete attributes.class

      let ctxFill = (getContextAttr(node, 'fill') || '').toLowerCase()
      let ctxStroke = (getContextAttr(node, 'stroke') || '').toLowerCase()
      let attrFill = (attributes.fill || '').toLowerCase()
      let attrStroke = (attributes.stroke || '').toLowerCase()

      if (attrFill) {
        if (!ctxFill) {
          if (attrFill !== 'none') {
            attributes.fill = 'currentColor'
            console.log(`  fill: ${attrFill} → currentColor`)
          }
        } else {
          if (attrFill === ctxFill) {
            delete attributes.fill
            console.log(`  fill: ${attrFill} → / (same as context)`)
          } else if (attrFill !== 'none') {
            attributes.fill = 'currentColor'
            console.log(
              `  fill: ${attrFill} → currentColor (different from context)`
            )
          }
        }
      }

      if (attrStroke) {
        if (!ctxStroke) {
          if (attrStroke !== 'none') {
            attributes.stroke = 'currentColor'
            console.log(`  stroke: ${attrStroke} → currentColor`)
          } else {
            delete attributes.stroke
            console.log(`  stroke: ${attrStroke} → / (same as default)`)
          }
        } else {
          if (attrStroke && attrStroke === ctxStroke) {
            delete attributes.stroke
            console.log(`  stroke: ${attrStroke} → / (same as context)`)
          } else if (attrStroke !== 'none') {
            attributes.stroke = 'currentColor'
            console.log(
              `  stroke: ${attrStroke} → currentColor (different from context)`
            )
          }
        }
      }
    },
  })

  return {
    el,
    content: stringify(el),
    width,
    height,
  }
}