飘云阁

 找回密码
 加入我们

QQ登录

只需一步,快速开始

查看: 1791|回复: 9

[已解决] 关于golang下生成pem格式的rsa密钥对问题

[复制链接]
  • TA的每日心情
    开心
    2018-10-30 22:05
  • 签到天数: 6 天

    [LV.2]偶尔看看I

    发表于 2023-5-13 14:38:47 | 显示全部楼层 |阅读模式
    本帖最后由 iamok 于 2023-5-29 15:25 编辑

    我又来求助了
    先上我的代码:

    [Golang] 纯文本查看 复制代码
    package main
    
    import (
            "crypto/rsa"
            "crypto/x509"
            "encoding/pem"
            "fmt"
            "math/big"
            "os"
    )
    
    func main() {
            pStr := "2"
            p, _ := new(big.Int).SetString(pStr, 10)
            qStr := "371184279057166373123655688640780598754149899440199546719492665055664482527399827955192609227660726572858487513363702798987332296114061468486398685486327249209739103979041586630882025554584761790082686315721947126433764515781192309840152107288321500200638494580875391919058645533176457386710195019213926805018659264622317769767365830081974666146195353145323624539152261704595085312203212605975554502308172822454500476768876526902862831528598244873004418597389417725953257870960718820300995263547910701494987918993055620653343397547627168097560657764403696854456783166762913641336473211771521309773368447506587130609090454859187247423522628607017541871404625615122000539738359669842550291081301225159722294350618597471573788342645747006205589475172909401378598368871837505687361299868427968066583312923659704388527184928608886065058856827717111096783348158889321482280831613046901620008117492377505276967846056907441196803149057457218090420675140832212078181378348118540222339544714975817376552010421963546506240227601553472506085686775145350904403451222791291617755195308494695859622340675249927811904203222993959833519691225404168863499560280359613632127412647839816179732483773258614700040469665956878922370480240267466872231677127"
            q, _ := new(big.Int).SetString(qStr, 10)
            nStr := "742368558114332746247311377281561197508299798880399093438985330111328965054799655910385218455321453145716975026727405597974664592228122936972797370972654498419478207958083173261764051109169523580165372631443894252867529031562384619680304214576643000401276989161750783838117291066352914773420390038427853610037318529245306582880498166585502933415522882566875637754584395147429486462461465428006888641232554161537770786321398660441068214789985841384100395365475690494547349212851591810310796140643125554242288844437464113972593802552073928040965680067257460730519659908215131131930004273494106699524090366445559074651750840824046383709628150729203983946224391790267067804864941917643070961741587145569561224237353498966742693768409768181496092835995647410222904941498598858417345534856013160827155487811451531908887619084841728272713750900271705699550306056804281582185919283045948771642385564345125610849744901427768987750851679327749285409776084062902092880751096107537423116352545877638437890989359891084289981763502169559051718629413572950960865843356191544723986721591889115821262521053599657989795316626712754149926230375843654207773966820822728595974685492966308669585449202982952586470899079301221700974590528885367306096187791"
            n, _ := new(big.Int).SetString(nStr, 10)
            eStr := "65537"
            e, _ := new(big.Int).SetString(eStr, 10)
    
            // 计算 D
            phiN := new(big.Int).Mul(new(big.Int).Sub(p, big.NewInt(1)), new(big.Int).Sub(q, big.NewInt(1)))
            d := new(big.Int).ModInverse(e, phiN)
            fmt.Println("d:\n" + d.Text(10))
    
            // 创建RSA私钥
            privateKey := &rsa.PrivateKey{
                    PublicKey: rsa.PublicKey{
                            N: n,
                            E: int(e.Int64()),
                    },
                    D:      d,
                    Primes: []*big.Int{p, q},
            }
    
            //生成PEM格式的私钥
            privateKeyPEM := &pem.Block{
                    Type:  "PRIVATE KEY",
                    Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
            }
    
            // 生成PEM格式的公钥
            publicKeyBytes, _ := x509.MarshalPKIXPublicKey(&privateKey.PublicKey)
    
            publicKeyPEM := &pem.Block{
                    Type:  "PUBLIC KEY",
                    Bytes: publicKeyBytes,
            }
    
            fmt.Println("privateKeyPEM:")
            _ = pem.Encode(os.Stdout, privateKeyPEM)
            fmt.Println("publicKeyPEM:")
            _ = pem.Encode(os.Stdout, publicKeyPEM)
    }


    问题描述:
    1.先排除我的测试数据中密钥的安全问题,只是为了测试而已
    2.我代码中到生成的d应该没有问题,我使用rsatool进行计算测试,也和我的结果一样,然后在这个工具里进行了加密解密的测试也是正常的,说明我的nepq是没问题的。

    3.问题就是最后生成pem格式的私钥和公钥拿出来就没办法进行加密解密

    今天问了半天gpt也没解决问题,求论坛大佬们帮忙看看。

    --------------------------------------------------------------------------------------
    不再纠结新的N、E、D生成的pem格式私钥的问题:
    1.不转PEM格式前的私钥和公钥可以正常加解密
    2.转PEM格式的代码在正常的N、E、D生成的密钥对也没问题
    3.猜测可能是我的1字节替换后的N安全性太低,导致golang内部未公开方法不兼容导致

    本帖子中包含更多资源

    您需要 登录 才可以下载或查看,没有账号?加入我们

    x
    PYG19周年生日快乐!
  • TA的每日心情
    开心
    2019-2-26 11:14
  • 签到天数: 459 天

    [LV.9]以坛为家II

    发表于 2023-5-13 20:21:36 | 显示全部楼层
    本帖最后由 wgz001 于 2023-5-13 21:40 编辑

    可以再生成一对公钥私钥试一下,有可能这一对不合适

    问题出现在这一条:
    2.我代码中到生成的d应该没有问题,我使用rsatool进行计算测试,也和我的结果一样,然后在这个工具里进行了加密解密的测试也是正常的,说明我的nepq是没问题的。


    点评

    感谢指点,我再测试一下。  详情 回复 发表于 2023-5-14 01:05
    PYG19周年生日快乐!
    回复 支持 反对

    使用道具 举报

  • TA的每日心情
    开心
    2018-10-30 22:05
  • 签到天数: 6 天

    [LV.2]偶尔看看I

     楼主| 发表于 2023-5-14 01:05:35 | 显示全部楼层
    wgz001 发表于 2023-5-13 20:21
    可以再生成一对公钥私钥试一下,有可能这一对不合适

    问题出现在这一条:

    感谢指点,我再测试一下。
    PYG19周年生日快乐!
    回复 支持 反对

    使用道具 举报

  • TA的每日心情
    擦汗
    前天 12:47
  • 签到天数: 102 天

    [LV.6]常住居民II

    发表于 2023-5-14 14:06:59 | 显示全部楼层
    感谢指点,我再测试一下
    PYG19周年生日快乐!
    回复 支持 反对

    使用道具 举报

  • TA的每日心情
    开心
    2018-10-30 22:05
  • 签到天数: 6 天

    [LV.2]偶尔看看I

     楼主| 发表于 2023-5-24 08:52:24 | 显示全部楼层
    本帖最后由 iamok 于 2023-5-24 09:19 编辑

    我发下我的完整代码,大佬们能否抽空帮忙分析下哪里出的问题

    [Golang] 纯文本查看 复制代码
    package main
    
    import (
            "crypto/rsa"
            "crypto/x509"
            "encoding/pem"
            "flag"
            "fmt"
            "math"
            "math/big"
            "os"
            "strconv"
            "strings"
            "time"
    )
    
    type Rsa struct {
            N string
            E string
            P string
            Q string
    }
    
    type Pemtype struct {
            PrivateType string
            PublicType  string
    }
    
    var (
            nString string
            eString string
            keyFile string
            qBit    int
    )
    
    func patchKeyfile(keyFile string, qBit int) {
            ticker := time.Tick(time.Minute)
            startTime := time.Now()
            go func() {
                    for range ticker {
                            fmt.Println("已执行", time.Since(startTime))
                    }
            }()
            pemdata, err := os.ReadFile(keyFile)
            if err != nil {
                    fmt.Println("keyfile错误")
                    return
            }
            block, _ := pem.Decode(pemdata)
            if block == nil || block.Type != "PUBLIC KEY" {
                    // 处理解码错误或不是公钥类型错误
                    fmt.Println("keyfile错误")
                    return
            }
    
            newrsa, res := attackPEM(block.Bytes, qBit)
    
            if res {
                    fmt.Println("新N为:")
                    fmt.Println(newrsa.N)
                    fmt.Println("新E为:")
                    fmt.Println(newrsa.E)
                    fmt.Println("新P为:")
                    fmt.Println(newrsa.P)
                    fmt.Println("新Q为:")
                    fmt.Println(newrsa.Q)
                    printKey(newrsa, 10, block.Type)
            } else {
                    fmt.Println("生成失败")
            }
            fmt.Println("程序执行了", time.Since(startTime))
    }
    
    func attackPEM(blockbytes []byte, qBit int) (Rsa, bool) {
            newS := Rsa{}
            fmt.Println("正在生成素数合集")
            primes := genPrimesMap(qBit)
            fmt.Println("素数合集生成完毕")
            for i, primesOfDigit := range primes {
                    fmt.Println("当前正在使用" + strconv.Itoa(i+1) + "位素数合集尝试分解")
                    ch := make(chan Rsa, len(blockbytes))
                    for i := range blockbytes {
                            go replaceAndCheck2(blockbytes, primesOfDigit, i, ch)
                    }
                    for range blockbytes {
                            newS = <-ch
                            if newS.N != "" {
                                    return newS, true
                            }
                    }
            }
            return Rsa{}, false
    }
    
    func replaceAndCheck2(blockbytes []byte, primes []int, idx int, ch chan<- Rsa) {
            newblock := make([]byte, len(blockbytes))
            copy(newblock, blockbytes)
            for i := 0; i < 255; i++ {
                    newblock[idx] = byte(i)
                    publicKeyInterface, err := x509.ParsePKIXPublicKey(newblock)
                    if err != nil {
                            // 处理解析错误
                            continue
                    }
                    publicKey, ok := publicKeyInterface.(*rsa.PublicKey)
                    if !ok {
                            // 处理不是RSA公钥类型错误
                            continue
                    }
                    nString = publicKey.N.Text(10)
                    eString = strconv.Itoa(publicKey.E)
    
                    n := publicKey.N
                    e := big.NewInt(int64(publicKey.E))
                    newRsa := Rsa{}
                    for _, p := range primes {
                            P, _ := new(big.Int).SetString(strconv.Itoa(p), 10)
                            q, r := new(big.Int).QuoRem(n, P, new(big.Int).SetInt64(0))
                            if q.ProbablyPrime(10) && r.Text(10) == "0" { //验证次数,越大结果越准确,但影响速度
                                    phi := new(big.Int).Mul(new(big.Int).Sub(P, big.NewInt(1)), new(big.Int).Sub(q, big.NewInt(1)))
                                    if new(big.Int).(nil, nil, e, phi).Cmp(big.NewInt(1)) == 0 {
                                            newRsa.N = nString
                                            newRsa.E = eString
                                            newRsa.P = P.Text(10)
                                            newRsa.Q = q.Text(10)
                                            ch <- newRsa
                                    }
                            }
                    }
            }
            ch <- Rsa{}
    }
    
    func patchN(nString string, eString string, qBit int) {
            ticker := time.Tick(time.Minute)
            startTime := time.Now()
            go func() {
                    for range ticker {
                            fmt.Println("已执行", time.Since(startTime))
                    }
            }()
    
            base := 10
            if nString == "" {
                    fmt.Println("n值异常")
                    return
            }
            var dorh bool
            _, dorh = new(big.Int).SetString(nString, 10)
            if !dorh {
                    _, dorh = new(big.Int).SetString(nString, 16)
                    if !dorh {
                            fmt.Println("n值异常!")
                            return
                    }
                    base = 16
            }
            var newrsa Rsa
            newrsa, res := attackN(nString, eString, base, qBit)
    
            if res {
                    fmt.Println("新N为:")
                    fmt.Println(newrsa.N)
                    fmt.Println("新E为:")
                    fmt.Println(newrsa.E)
                    fmt.Println("新P为:")
                    fmt.Println(newrsa.P)
                    fmt.Println("新Q为:")
                    fmt.Println(newrsa.Q)
                    printKey(newrsa, base, "")
            } else {
                    fmt.Println("生成失败")
            }
            fmt.Println("程序执行了", time.Since(startTime))
    }
    
    func main() {
    
            flag.StringVar(&nString, "n", "", "设置输入的n参数")
            flag.StringVar(&eString, "e", "", "设置输入的e参数")
            flag.StringVar(&keyFile, "key", "", "输入pem格式key文件路径")
            flag.IntVar(&qBit, "b", 3, "生成用于分解的素数合集,默认为3位以内,过大影响生成时间与执行效率")
            flag.Parse()
    
            if keyFile != "" {
                    patchKeyfile(keyFile, qBit)
            } else {
                    patchN(nString, eString, qBit)
            }
    }
    
    func genPrimesMap(qBit int) [][]int {
            primes := make([][]int, qBit)
            for i := 1; i <= qBit; i++ {
                    previousPrimes := make([]int, 0)
                    if i > 1 {
                            previousPrimes = primes[i-2]
                    }
                    start := int(math.Pow10(i-1)) + 1
                    end := int(math.Pow10(i)) - 1
                    primes[i-1] = generatePrimes(start, end, previousPrimes)
            }
            return primes
    }
    func attackN(nStr string, eStr string, base int, qBit int) (Rsa, bool) {
    
            newS := Rsa{}
            fmt.Println("正在生成素数合集")
            primes := genPrimesMap(qBit)
            fmt.Println("素数合集生成完毕")
            for i, primesOfDigit := range primes {
                    fmt.Println("当前正在使用" + strconv.Itoa(i+1) + "位素数合集尝试分解")
                    ch := make(chan Rsa, len(nStr))
                    for i := range nStr {
                            go replaceAndCheck(nStr, eStr, primesOfDigit, base, i, ch)
                    }
                    for range nStr {
                            newS = <-ch
                            if newS.N != "" {
                                    return newS, true
                            }
                    }
            }
    
            return Rsa{}, false
    }
    
    func replaceAndCheck(nStr string, eStr string, primes []int, base, idx int, ch chan<- Rsa) {
            newRsa := Rsa{}
            e, _ := new(big.Int).SetString(eStr, base)
            for i := 0; i < base; i++ {
                    newN := nStr[:idx] + strconv.FormatInt(int64(i), base) + nStr[idx+1:]
                    n, _ := new(big.Int).SetString(newN, base)
                    for _, p := range primes {
                            P, _ := new(big.Int).SetString(strconv.Itoa(p), base)
                            q, r := new(big.Int).QuoRem(n, P, new(big.Int).SetInt64(0))
                            if q.ProbablyPrime(10) && r.Text(10) == "0" { //验证次数,越大结果越准确,但影响速度
                                    phi := new(big.Int).Mul(new(big.Int).Sub(P, big.NewInt(1)), new(big.Int).Sub(q, big.NewInt(1)))
                                    if new(big.Int).**(nil, nil, e, phi).Cmp(big.NewInt(1)) == 0 {
                                            newRsa.N = newN
                                            newRsa.E = eStr
                                            newRsa.P = P.Text(base)
                                            newRsa.Q = q.Text(base)
                                            ch <- newRsa
                                    }
    
                            }
                    }
            }
            ch <- Rsa{}
    }
    
    func isPrime(num int) bool {
            if num < 2 {
                    return false
            }
            for i := 2; i <= int(math.Sqrt(float64(num))); i++ {
                    if num%i == 0 {
                            return false
                    }
            }
            return true
    }
    
    func printKey(newrsa Rsa, base int, blocktype string) {
            pemtype := new(Pemtype)
            pStr := newrsa.P
            p, _ := new(big.Int).SetString(pStr, base)
            qStr := newrsa.Q
            q, _ := new(big.Int).SetString(qStr, base)
            nStr := newrsa.N
            n, _ := new(big.Int).SetString(nStr, base)
            eStr := newrsa.E
            e, _ := new(big.Int).SetString(eStr, base)
    
            // 计算 D
            phiN := new(big.Int).Mul(new(big.Int).Sub(p, big.NewInt(1)), new(big.Int).Sub(q, big.NewInt(1)))
            d := new(big.Int).ModInverse(e, phiN)
            fmt.Println("新D为:\n" + d.Text(base))
            // 创建RSA私钥
            //privateKey := &rsa.PrivateKey{
            //        PublicKey: rsa.PublicKey{
            //                N: n,
            //                E: int(e.Int64()),
            //        },
            //        D:      d,
            //        Primes: []*big.Int{p, q},
            //}
            //privateKey.Precompute()
            //
            //err := privateKey.Validate()
            //if err != nil {
            //        fmt.Println(err)
            //        return
            //}
            publicKey := &rsa.PublicKey{
                    N: n,
                    E: int(e.Int64()),
            }
            if strings.Index(blocktype, "RSA") == -1 {
                    pemtype.PrivateType = "PRIVATE KEY"
                    pemtype.PublicType = "PUBLIC KEY"
            } else {
                    pemtype.PrivateType = "RSA PRIVATE KEY"
                    pemtype.PublicType = "RSA PUBLIC KEY"
            }
    
            //生成PEM格式的私钥
            //privateKeyPEM := &pem.Block{
            //        Type:  pemtype.PrivateType,
            //        Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
            //}
    
            // 生成PEM格式的公钥
            publicKeyBytes, _ := x509.MarshalPKIXPublicKey(publicKey)
    
            publicKeyPEM := &pem.Block{
                    Type:  pemtype.PublicType,
                    Bytes: publicKeyBytes,
            }
            fmt.Println("publicKeyPEM:")
            _ = pem.Encode(os.Stdout, publicKeyPEM)
    }
    
    func generatePrimes(start, end int, previousPrimes []int) []int {
            primes := make([]int, 0)
            for i := start; i <= end; i++ {
                    isValid := true
                    for _, prime := range previousPrimes {
                            if i%prime == 0 {
                                    isValid = false
                                    break
                            }
                    }
                    if isValid && isPrime(i) {
                            primes = append(primes, i)
                    }
            }
            return primes
    }
    


    我用来测试分解的数据为:
    [AppleScript] 纯文本查看 复制代码
    模数N:742368558114332746247311377281561197508299798880399093438985330111328965054799655910385218455321453145716975026727405597974664592228122936972797370972654498419478207958083173261764051109169523580165372631443894252867529031562384619680304214576643000401276989161750783838117291066352914773420390038427853610037318529245306582880498166585502933415522882566875637754584395147429486462461465428006888641232554597141870693612099265096122381848819548659061233927571663495116029299344233004713796086749474084904157247082775856931058513039459592247297453741363415148755948913271102348378415607627392082839207009920183086463382333631126385164879853232391935507538829006688268914101594335327634763820416152328493936426564576205297560095286032733535397819127322749323749685575383720038790064733568683732604591147260284993313505283944344245845548004947067351613510387100697614788589569107156229477938758417852961460627714901119392189242006056624460564177601478701187445331548369703970196610712955164819181091851374733353573483397265010686764487768118112312125748720430233765569622536424634486156202792655306890425614062298626685126742438296068739196365662741038218776023610118804911401892651297681884655867945598479712597939521037620140589160847
    公钥E:65537



    我用我的代码生成的数据为:
    [AppleScript] 纯文本查看 复制代码
    新N为:
    742368558114332746247311377281561197508299798880399093438985330111328965054799655910385218455321453145716975026727405597974664592228122936972797370972654498419478207958083173261764051109169523580165372631443894252867529031562384619680304214576643000401276989161750783838117291066352914773420390038427853610037318529245306582880498166585502933415522882566875637754584395147429486462461465428006888641232554597141870693612099265096122381848819548659061233927571663495116029299344233004713796086749474084904157247082775856931058513039459592247297453741363415148755948913271102348378415607627392082839207009920183086463382333631126385164879853232391935507538829006688268914101594335327634763820416152328493936426564576205297520095286032733535397819127322749323749685575383720038790064733568683732604591147260284993313505283944344245845548004947067351613510387100697614788589569107156229477938758417852961460627714901119392189242006056624460564177601478701187445331548369703970196610712955164819181091851374733353573483397265010686764487768118112312125748720430233765569622536424634486156202792655306890425614062298626685126742438296068739196365662741038218776023610118804911401892651297681884655867945598479712597939521037620140589160847
    新E为:
    65537
    新P为:
    3
    新Q为:
    247456186038110915415770459093853732502766599626799697812995110037109655018266551970128406151773817715238991675575801865991554864076040978990932456990884832806492735986027724420588017036389841193388457543814631417622509677187461539893434738192214333467092329720583594612705763688784304924473463346142617870012439509748435527626832722195167644471840960855625212584861465049143162154153821809335629547077518199047290231204033088365374127282939849553020411309190554498372009766448077668237932028916491361634719082360925285643686171013153197415765817913787805049585316304423700782792805202542464027613069003306727695487794111210375461721626617744130645169179609668896089638033864778442544921273472050776164645475521525401765840031762010911178465939709107583107916561858461240012930021577856227910868197049086761664437835094648114748615182668315689117204503462366899204929529856369052076492646252805950987153542571633706464063080668685541486854725867159567062481777182789901323398870237651721606393697283791577784524494465755003562254829256039370770708582906810077921856540845474878162052067597551768963475204687432875561708914146098689579732121887580346072925341203372934970467297550432560628218622648532826570865979840345873380196386949
    新D为:
    171565896839948178504688620478607899315817152964623413784989728090486114785846095921673169640421421934861670564029682243418592091702201046788684086558002731786035627778707108079751565041113899082124368431204498563466920895250680950450552933975888961717468625018598308924914544310709694480342786937486126474779517317606076163149183289303813531737972589214610043325616602055372797075857017491990666880695000868643831324678408463450354297503428916245634396586157444120069996792161187620571511596959084707721720030888135299587680428437304957263493404250525509038299855077901095811046271309231800059305165469463831011910438207808978748336165376154810385815603141799827586263835432622837059312034789859822197677054438669319703926627145005901736837746135807717186589449283988614427079578260442670305537774654262542937710397958872408531784742513128893329074236359965014664595388522722995990839874581305168087557908774736291778905019445866207395512535422005834996796420215017586040444296593655781106112834233805662623757937951614749711792345266580968446518098022790733793327700427799373085849548308551768896385039757504539417015268336518794835342907889098917632201377139613644493768299832103310951447240122435182778079686161796173072453170425




    本帖子中包含更多资源

    您需要 登录 才可以下载或查看,没有账号?加入我们

    x
    PYG19周年生日快乐!
    回复 支持 反对

    使用道具 举报

  • TA的每日心情
    难过
    2024-4-22 14:49
  • 签到天数: 11 天

    [LV.3]偶尔看看II

    发表于 2023-5-24 11:02:50 | 显示全部楼层
    你这是1字节PatchN吧? 这么大能分解?

    点评

    是的飘总,我用下面的代码验证时好像又可以正确的加解密: [mw_shl_code=golang,true]package main import ( "crypto/rand" "crypto/rsa" "fmt" "math/big" ) func main() { nStr := "742368558  详情 回复 发表于 2023-5-24 11:35
    PYG19周年生日快乐!
    回复 支持 反对

    使用道具 举报

  • TA的每日心情
    开心
    2018-10-30 22:05
  • 签到天数: 6 天

    [LV.2]偶尔看看I

     楼主| 发表于 2023-5-24 11:35:56 | 显示全部楼层
    飘云 发表于 2023-5-24 11:02
    你这是1字节PatchN吧? 这么大能分解?

    是的飘总,我用下面的代码验证时好像又可以正确的加解密:

    [Golang] 纯文本查看 复制代码
    package main
    
    import (
    	"crypto/rand"
    	"crypto/rsa"
    	"fmt"
    	"math/big"
    )
    
    func main() {
    	nStr := "742368558114332746247311377281561197508299798880399093438985330111328965054799655910385218455321453145716975026727405597974664592228122936972797370972654498419478207958083173261764051109169523580165372631443894252867529031562384619680304214576643000401276989161750783838117291066352914773420390038427853610037318529245306582880498166585502933415522882566875637754584395147429486462461465428006888641232554597141870693612099265096122381848819548659061233927571663495116029299344233004713796086749474084904157247082775856931058513039459592247297453741363415148755948913271102348378415607627392082839207009920183086463382333631126385164879853232391935507538829006688268914101594335327634763820416152328493936426564576205297520095286032733535397819127322749323749685575383720038790064733568683732604591147260284993313505283944344245845548004947067351613510387100697614788589569107156229477938758417852961460627714901119392189242006056624460564177601478701187445331548369703970196610712955164819181091851374733353573483397265010686764487768118112312125748720430233765569622536424634486156202792655306890425614062298626685126742438296068739196365662741038218776023610118804911401892651297681884655867945598479712597939521037620140589160847"
    	eStr := "65537"
    	dStr := "171565896839948178504688620478607899315817152964623413784989728090486114785846095921673169640421421934861670564029682243418592091702201046788684086558002731786035627778707108079751565041113899082124368431204498563466920895250680950450552933975888961717468625018598308924914544310709694480342786937486126474779517317606076163149183289303813531737972589214610043325616602055372797075857017491990666880695000868643831324678408463450354297503428916245634396586157444120069996792161187620571511596959084707721720030888135299587680428437304957263493404250525509038299855077901095811046271309231800059305165469463831011910438207808978748336165376154810385815603141799827586263835432622837059312034789859822197677054438669319703926627145005901736837746135807717186589449283988614427079578260442670305537774654262542937710397958872408531784742513128893329074236359965014664595388522722995990839874581305168087557908774736291778905019445866207395512535422005834996796420215017586040444296593655781106112834233805662623757937951614749711792345266580968446518098022790733793327700427799373085849548308551768896385039757504539417015268336518794835342907889098917632201377139613644493768299832103310951447240122435182778079686161796173072453170425"
    
    	n, _ := new(big.Int).SetString(nStr, 10)
    	e, _ := new(big.Int).SetString(eStr, 10)
    
    	d, _ := new(big.Int).SetString(dStr, 10)
    
    	privKey := &rsa.PrivateKey{
    		PublicKey: rsa.PublicKey{
    			N: n,
    			E: int(e.Int64()),
    		},
    		D: d,
    	}
    
    	pubKey := &privKey.PublicKey
    
    	// 定义需要加密的明文m
    	m := []byte("hello world")
    
    	// 使用公钥进行加密
    	c, err := rsa.EncryptPKCS1v15(rand.Reader, pubKey, m)
    	if err != nil {
    		fmt.Println(err)
    		return
    	}
    	// 使用私钥进行解密
    	m2, err := rsa.DecryptPKCS1v15(rand.Reader, privKey, c)
    	if err != nil {
    		fmt.Println("err")
    		return
    	}
    	// 检查解密后的结果是否与原始明文相同
    	if string(m) != string(m2) {
    		fmt.Println("解密失败")
    		return
    	}
    	fmt.Println("解密正确.")
    }
    

    但是转pem格式的用其他工具验证好像就不行了,是我生成pem格式代码的问题吗?
    PYG19周年生日快乐!
    回复 支持 反对

    使用道具 举报

  • TA的每日心情
    难过
    2024-4-22 14:49
  • 签到天数: 11 天

    [LV.3]偶尔看看II

    发表于 2023-5-24 14:43:27 | 显示全部楼层
    生成pem格式就那么几句,只要p、q、n、d、e无错,那就不会错,另外有的工具生成的数据要逆转过来使用
    PYG19周年生日快乐!
    回复 支持 反对

    使用道具 举报

  • TA的每日心情
    慵懒
    昨天 09:32
  • 签到天数: 2634 天

    [LV.Master]伴坛终老

    发表于 2023-5-24 18:22:09 | 显示全部楼层
    Change byte at index: 17 From: 4F To: 40
    New Private key: 38FA6FE5FE9F6FAD55E952302F82A85DF17738309C4044131CF24EE21032823B62CC4689FCC70127A80FB84AF54A63CD430849B298EB7EC101AC0496DBC33045505EAF8097A35350CF4409AAA952976DF8B47E55B2E702950206EB97824DA938A27773E64EE709340DE50DD6D3539FC1D1D75E142187E510B9FC886510B317263A2943C19C99E9F80790A5A4D02A818A125348327EB63D40CA3FD2EAAB38B5333EB2E4D9A7678033C49DBFE0CBC35119C435D5FC2C607D4314851A66D92751293C927AA7627F62C2ED6A205C25F90004CD57522FE099F6DCC8731C8A0EAC4505C5E62FE2894E08BABA010AB6B5F04707664A1864C6C39DD5A3425C49781ED12C88BFF1F9691AF478A0D93762D54C60CFACDBB5788BEC281E9E36B68D87692E75BC412C44C8498C007503B313A190B8755D2FDEA4C31431F8ECC30927EB2CB0B53CD2E252DE1BF7ABB443E71A3F49AE66C811DB9B2C65A0ED94C2FC0E5D7E6AB8DAA91DFE1DBC43EDFDFA257BFFD22E26E7E9603CB0EDFA4C2C5799FF7F4A1F595DEB720AEFFED167D59F849E640606838D06767C3FE8F30305BE384F0C6810B4B4561BF6DA82311BDD7888E245B79669CA34A6DEA157EE338E857A21F776DD86959B8F0D1450B361A7FF0274DAA6F8DFC9E51AC3B2C192450C56CCB0E5AE01286E1AFFF44BF73029D8D93891C2C6BBA965B510C423EA1FE1FBFF9A920128F7BF
    New Modulus: 00B5F80D476049A19FA344D3720E2EA14F4072B0EB2F475FA9C90D8221B2301BEAF47B3853F92D1248BE9C510572468C23DD16D9D33289987047D1ABC7913F4FA8C85951D08F2990F2F2269BFF16D51B96DCB6C5A81DCC98B1CD39CAC30EE5B58D801509971EB7C229949A96529302E52F29BE67C2D14E69B89B27B677996846DFE4A5FDDD7FA04615804A0455A6B1FD6FF62FC2CB743D2D55A8E83320F924B8217B513E84E97F3A5629A91AEA59F243675271469242FFC88E3CCE39427FB248D60B0CA0A6D4958433A617D974A21700FBA9C62F51FBB4E4C6BE57B6365B38B1F8209592A727BD756975E609341763F97584CA5417B129A95D36ED71A867CBB888F32B4F52162F665A35FD6EDDBD593C37B5975D1450729EFDCBCBD065F86C8E59FA927CFFCB7BF7CA9E9C0388D8B874BE0A4515A6ECC352761F696021C9578F8C99A4D8C9B39D0539128BA3366EF3B54E297333EBE3EA8F3A7771654D33CB2892795B5017B2FBE43BDAA065AC5BD7E7A98C827D9971E491FC10DD09684B781AE3C8EBA0B874C9C37AB467DEBD8DB5817F79FE527E66E24EF770672B4AAC0500FEC0C634FB20CF5484DDC2D3AFB17AFE2EF0530C144FDF4285DDB4E230B28D8DD25B0502BD7015DA3AE638F110D15429C03CBD544760491DCF8133B266CC807A6F7154184AE628654F64267D9C5DC4B96168DBBDB2A36D177122703B80409B998F
    试试这一组

    点评

    这组我看了下新的n为一个素数,这个时候应该p=1,q=n 用我楼上的代码也是可以成功加解密的, 但是用golang生成pem格式时就直接报错了, 执行x509.MarshalPKCS1PrivateKey(privatekey)命令时就报错了,提示:pan  详情 回复 发表于 2023-5-24 23:15
    PYG19周年生日快乐!
    回复 支持 反对

    使用道具 举报

  • TA的每日心情
    开心
    2018-10-30 22:05
  • 签到天数: 6 天

    [LV.2]偶尔看看I

     楼主| 发表于 2023-5-24 23:15:24 | 显示全部楼层
    email123 发表于 2023-5-24 18:22
    Change byte at index: 17 From: 4F To: 40
    New Private key: 38FA6FE5FE9F6FAD55E952302F82A85DF17738309 ...

    这组我看了下新的n为一个素数,这个时候应该p=1,q=n

    用我楼上的代码也是可以成功加解密的,
    但是用golang生成pem格式时就直接报错了,
    执行x509.MarshalPKCS1PrivateKey(privatekey)命令时就报错了,提示:panic: division by zero

    PYG19周年生日快乐!
    回复 支持 反对

    使用道具 举报

    您需要登录后才可以回帖 登录 | 加入我们

    本版积分规则

    快速回复 返回顶部 返回列表