Generate prime number using OpenSSL

后端 未结 2 1122
-上瘾入骨i
-上瘾入骨i 2021-01-05 05:02

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

相关标签:
2条回答
  • 2021-01-05 05:22

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

    $ openssl prime -generate -bits 2048 -hex
    D668FDB1968891AE5D858E641B79C4BA18ABEF8C571CBE004EA5673FB3089961E4670681B794063592124D13FF553BBD5CCC81106A9E5F7D87370DD5DA6342B1DAC13CD2E584759CDEC3E76AEFB799848E48EA9C218F53FE3103E1081B8154AD41DDCB931175853FE3D433CECD886B4D94C211EAE01AE5EA93F8FBD6812A9DEF0308378EE963B3C39F80865BA0E1D957683F4ED77ADA9812091AA42E9A56F43C37185223FF9E3DD03C312E71DED072E5686873B3CA6F5F575C569FB0A10CFEA17D7FEB898A8A02549FF6E4B7A1FBCE78656D3DCF227318EEEF8E601C23AA32DF41A61F04D39FC752F70A809D636238340B7B929F0CDBA629F7DE6AAAC44D2BA5
    
    0 讨论(0)
  • 2021-01-05 05:27

    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

    0 讨论(0)
提交回复
热议问题