Node.js crypto.checkPrime()函数


Node.js crypto.checkPrime()函数

crypto.checkPrime()是加密模块中 Crypto 类的内置应用程序编程接口,用于检查传递的缓冲区对象是否为素数。

句法:

const crypto.checkPrime(candidate[, options, [callback]])

参数:此 API 将以下参数作为参数。

  • 候选:它是一个缓冲区对象,表示任意长度的大端字节序列。
  • option:任何其他会改变此 API 操作的选项。
  • callback:是执行的回调函数,作为可选参数传递。

返回值:当且仅当候选是素数时,此 API 才返回 true。

示例 1:

index.js
// Node.js program to demonstrate the  
// crypto.checkPrime() api
  
// Importing crypto module
const crypto = require('crypto')
  
// Creating and ini
tializing new 
// ArrayBuffer object
const buffer = new ArrayBuffer(8)
  
// Checking if the buffer object is prime or not
// by using checkPrime() method
crypto.checkPrime(buffer, (err, val) => {
  
    // Checking if any error is found
    if (err) throw new Error('Uh oh!');
  
    // Display the result
    if (val)
        console.log("candidate is a prime")
    else
        console.log("candidate is not a prime")
})


index.js
// Node.js program to demonstrate the  
// crypto.checkPrime() api
  
// Importing crypto module
const crypto = require('crypto')
  
// Creating and initializing new 
// ArrayBuffer object
const buffer = BigInt("0o377777777777777777")
  
// Checking if the buffer object is prime or not
// by using checkPrime() method
crypto.checkPrime(buffer, (err, val) => {
  
    // Checking if any error is found
    if (err) throw new Error('Uh oh!');
  
    // Display the result
    if (val)
        console.log("candidate is a prime")
    else
        console.log("candidate is not a prime")
})


使用以下命令运行index.js文件:

node index.js

输出:

candidate is not a prime

示例 2:

index.js

// Node.js program to demonstrate the  
// crypto.checkPrime() api
  
// Importing crypto module
const crypto = require('crypto')
  
// Creating and initializing new 
// ArrayBuffer object
const buffer = BigInt("0o377777777777777777")
  
// Checking if the buffer object is prime or not
// by using checkPrime() method
crypto.checkPrime(buffer, (err, val) => {
  
    // Checking if any error is found
    if (err) throw new Error('Uh oh!');
  
    // Display the result
    if (val)
        console.log("candidate is a prime")
    else
        console.log("candidate is not a prime")
})

使用以下命令运行index.js文件:

node index.js

输出:

candidate is not a prime

参考:

https://nodejs.org/dist/latest-v15.x/docs/api/crypto.html#crypto_crypto_checkprime_candidate_options_callback



Made with ❤️ in Chengdu. Copyright reserved 2019-2022.

蜀ICP备20006366号-1