Generate prime number using OpenSSL

橙三吉。 提交于 2019-12-19 02:08:11

问题


How can I generate a large random prime using openssl, I found out how to generate a random number and check if it is prime but I have not been able to automate the process of checking the primality, here is the command that i am using: openssl rand -hex 256 | xargs openssl prime -hex

Should I use a while loop to repeatedly check if the result is prime? How can I automate the process of checking if the result does not contain the keyword "not",

This is all the further i got on writing the while loop:

while [{openssl rand -hex 256 | xargs openssl prime -hex} = *"$not"*]


回答1:


OpenSSL version 1.0.0 and newer adds -generate option to the prime command:

$ openssl prime -generate -bits 2048 -hex
D668FDB1968891AE5D858E641B79C4BA18ABEF8C571CBE004EA5673FB3089961E4670681B794063592124D13FF553BBD5CCC81106A9E5F7D87370DD5DA6342B1DAC13CD2E584759CDEC3E76AEFB799848E48EA9C218F53FE3103E1081B8154AD41DDCB931175853FE3D433CECD886B4D94C211EAE01AE5EA93F8FBD6812A9DEF0308378EE963B3C39F80865BA0E1D957683F4ED77ADA9812091AA42E9A56F43C37185223FF9E3DD03C312E71DED072E5686873B3CA6F5F575C569FB0A10CFEA17D7FEB898A8A02549FF6E4B7A1FBCE78656D3DCF227318EEEF8E601C23AA32DF41A61F04D39FC752F70A809D636238340B7B929F0CDBA629F7DE6AAAC44D2BA5



回答2:


There are better ways of generating prime numbers than by using openssl.

If you are really set on this method though, use something like this (call with a number range to be checked):

#!/bin/bash
# Usage: $0 <starting_number> <final_number>
N=$1
while (( N <= $2 )); do
  # use bc to convert hex to decimal
  openssl prime $N | awk '/is prime/ {print "ibase=16;"$1}' | bc
  let N++
done

If you want to do this with openssl-generated random numbers, use this (call with the number of attempts):

#!/bin/bash
# Usage: $0 <count>
N=$1
while (( N-- > 0 )); do
  # use bc to convert hex to decimal
  openssl rand -hex 256 | xargs openssl prime -hex | awk '/is prime/ {print "ibase=16;"$1}' | bc
done

If you don't care for decimal, replace awk '/is prime/ {print "ibase=16;"$1}' | bc with awk '/is prime/ {print $1}'

Adapted from: http://www.madboa.com/geek/openssl/#prime



来源:https://stackoverflow.com/questions/19732162/generate-prime-number-using-openssl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!