繁体   English   中英

如何通过加密提供程序生成大素数?

[英]How to generate a large prime via cryprography provider?

我想通过 Powershell 中的内置密码学提供程序生成一个 2048 位素数。这是我到目前为止的代码,但通过 Rabin-Miller 测试测试结果告诉我,这个数字不是素数。 这里有什么问题?

$rsa = [System.Security.Cryptography.RSA]::Create(2048)
$format = [System.Security.Cryptography.CngKeyBlobFormat]::GenericPrivateBlob
$bytes = $rsa.Key.Export($format)

[bigint]$prime = 0
foreach($b in $bytes) {$prime = ($prime -shl 8) + $b}
$prime

这个链接告诉我,BLOB 应该包含两个 RSA 素数,但出于任何原因我无法按预期获得该信息: https://learn.microsoft.com/en-us/windows/win32/seccrypto/rsa -schannel-key-blobs#private-key-blobs

在深入研究通用 BLOB 格式后,我终于解决了这个问题。 这里的学习点是一个 4096 RSA 密钥包含两个 2048 位素数的事实。 一个在 BLOB 的最后 256 个字节中,另一个素数在其前面的 256 个字节中。

这是工作代码:

# generating two random 2048-bit PRIME numbers:

cls
$rsa = [System.Security.Cryptography.RSA]::Create(4096)
$key = $rsa.Key.Export('PRIVATEBLOB')
$len = $key.Length

$Pb = [byte[]]::new(256+1)
[array]::Copy($key, $len-512, $Pb, 1, 256)
[array]::Reverse($Pb)
$P = [bigint]$Pb
write-host $P

# optionally same for the second prime in the BLOB:
$Qb = [byte[]]::new(256+1)
[array]::Copy($key, $len-256, $Qb, 1, 256)
[array]::Reverse($Qb)
$Q = [bigint]$Qb
write-host $Q

# optionally here the Test-Function:
function Is-PrimeRabinMiller ([BigInt] $Source, [int] $Iterate)  {
    if ($source -eq 2 -or $source -eq 3) {return $true}
    if (($source -band 1) -eq 0) {return $false}

    [BigInt]$d = $source - 1;
    $s = 0;
    while (($d -band 1) -eq 0) {$d = $d -shr 1; $s++;}

    if ($source.ToByteArray().Length -gt 255) {
        $sourceLength = 255
    }
    else {
        $sourceLength = $source.ToByteArray().Length
    }

    $rngProv = [System.Security.Cryptography.RNGCryptoServiceProvider]::Create()
    [Byte[]] $bytes = $sourceLength 

    [BigInt]$a = 0
    foreach ($i in 1..$iterate) {          
        do {
            $rngProv.GetBytes($bytes)
            $a = [BigInt]$bytes            
        } while (($a -lt 2) -or ($a -ge ($source - 2)))                              
     
        [BigInt]$x = ([BigInt]::ModPow($a,$d,$source))
        if ($x -eq 1 -or ($x -eq $source-1)) {continue}

        foreach ($j in 1..($s-1)) {            
            $x = [BigInt]::ModPow($x, 2, $source)
            if ($x -eq 1) {return $false}
            if ($x -eq $source-1) {break}
        }
        return $false
    }
    return $true
}

if (Is-PrimeRabinMiller $P 42) {"P is prime!"}
if (Is-PrimeRabinMiller $Q 42) {"Q is prime!"}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM