dongxiaoshe0737 2018-02-13 06:50
浏览 305
已采纳

无法从Golang中的iOS解析base64 DER编码的ASN.1公钥

i have a projects in Golang with RSA enryption, so now, i have a Base64 public key format which used for encrypt a message,

i used this code:

publicKeyBase64 = "MIGJAoGBAJJYXgBem1scLKPEjwKrW8+ci3B/YNN3aY2DJ3lc5e2wNc0SmFikDpow1TdYcKl2wdrXX7sMRsyjTk15IECMezyHzaJGQ9TinnkQixJ+YnlNdLC04TNWOg13plyahIXBforYAjYl2wVIA8Yma2bEQFhmAFkEX1A/Q1dIKy6EfQ+xAgMBAAE="
publicKeyBinary, err := base64.StdEncoding.DecodeString(publicKeyBase64)

publicKeyInterface, err := x509.ParsePKIXPublicKey(publicKeyBinary)
    if err != nil {
    fmt.Println("Could not parse DER encoded public key (encryption key)")
    return "","",err
}

publicKey, isRSAPublicKey := publicKeyInterface.(*rsa.PublicKey)
if !isRSAPublicKey {
    fmt.Println("Public key parsed is not an RSA public key")
    return "","",err
}

encryptedMessage, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey, "message")

When i run this code, i got this error:

Could not parse DER encoded public key (encryption key)

asn1: structure error: tags don't match (16 vs {class:0 tag:2 length:129 isCompound:false}) {optional:false explicit:false application:false defaultValue:<nil> tag:<nil> stringType:0 timeType:0 set:false omitEmpty:false} AlgorithmIdentifier @3

The error points to publicKeyInterface, it failed to parse from Base64 decoded format to public Key, What's the problem with my code ?

=======updated=====

my publicKeyBase64 is retrieved from my models with Binary Data type

When i store it in my mongoDB from my Rails API, i receive public_key params as Base64 format, but i decode it to binary and then i stored it with this code

def create
  params = device_params      
  public_key = Base64.decode64 device_params[:public_key]
  #device_params[:public_key] value is "MIGJAoGBAJJYXgBem1scLKPEjwKrW8+ci3B/YNN3aY2DJ3lc5e2wNc0SmFikDpow1TdYcKl2wdrXX7sMRsyjTk15IECMezyHzaJGQ9TinnkQixJ+YnlNdLC04TNWOg13plyahIXBforYAjYl2wVIA8Yma2bEQFhmAFkEX1A/Q1dIKy6EfQ+xAgMBAAE="
  params[:public_key] = BSON::Binary.new(public_key, :generic)
  device = Device.find_or_create_by(id: device_params[:id])

  render_success device.update_attributes(params), device
end

When i use rails code to convert my Base64 public key string using this code, it succeeded:

rsa_public_key = OpenSSL::PKey::RSA.new(Base64.decode64(public_key))

in my iOS app, i use https://github.com/DigitalLeaves/AsymmetricCrypto to generate a public Key using this code:

AsymmetricCryptoManager.sharedInstance.createSecureKeyPair({ (success, error) -> Void in
   if success {
    print("RSA-1024 keypair successfully generated.")
    let publicKey = AsymmetricCryptoManager.sharedInstance.getPublicKeyData()?.base64EncodedString()

    let url = ENV.BASE_URL + "devices"
    let headers = ["Authentication-Token": CurrentUser.getCurrentUser().token] as! HTTPHeaders
    let params = ["device[user_id]": CurrentUser.getCurrentUser().id!, "device[id]": instanceID,"device[token]": fcmToken, "device[os]": "ios", "device[public_key]": publicKey!]

    Alamofire.request(url, method: .post, parameters: params, encoding: URLEncoding.default, headers: headers)
} else { print("An error happened while generating a keypair: \(error)") }
})
  • 写回答

1条回答 默认 最新

  • 「已注销」 2018-02-13 09:17
    关注

    We can dump the ASN.1 contents to see what they look like:

    $ echo "MIGJAoGBAJJYXgBem1scLKPEjwKrW8+ci3B/YNN3aY2DJ3lc5e2wNc0SmFikDpow1TdYcKl2wdrXX7sMRsyjTk15IECMezyHzaJGQ9TinnkQixJ+YnlNdLC04TNWOg13plyahIXBforYAjYl2wVIA8Yma2bEQFhmAFkEX1A/Q1dIKy6EfQ+xAgMBAAE=" | \
        base64 -d | \
        dumpasn1 -
      0 137: SEQUENCE {
      3 129:   INTEGER
           :     00 92 58 5E 00 5E 9B 5B 1C 2C A3 C4 8F 02 AB 5B
           :     CF 9C 8B 70 7F 60 D3 77 69 8D 83 27 79 5C E5 ED
           :     B0 35 CD 12 98 58 A4 0E 9A 30 D5 37 58 70 A9 76
           :     C1 DA D7 5F BB 0C 46 CC A3 4E 4D 79 20 40 8C 7B
           :     3C 87 CD A2 46 43 D4 E2 9E 79 10 8B 12 7E 62 79
           :     4D 74 B0 B4 E1 33 56 3A 0D 77 A6 5C 9A 84 85 C1
           :     7E 8A D8 02 36 25 DB 05 48 03 C6 26 6B 66 C4 40
           :     58 66 00 59 04 5F 50 3F 43 57 48 2B 2E 84 7D 0F
           :     B1
    135   3:   INTEGER 65537
           :   }
    
    0 warnings, 0 errors.
    

    A well-formatted ASN.1 public key should include the algorithm as well. We should have a line similar to:

      5   9:     OBJECT IDENTIFIER rsaEncryption (1 2 840 113549 1 1 1)
    

    The AsymmetricCryptoManager.getPublicKeyData() returns a very barebones ASN.1 key, without any algorithm information. This makes Go very unhappy as it has no way of knowing what kind of key it is. See more about correctly exporting the key here.

    If you can change the iOS code, you should instead use CryptoExportImportManager and use one of exportPublicKeyToPEM or exportPublicKeyToDER. These take the output of getPublicKeyData and generate output usable by other tools. You can find an example of how to use them in the CryptoExportImportManager example.

    If you cannot change the key export code, you can instead parse it directly in Go. This assumes that you know for sure that it is a RSA public key:

    func main() {
        publicKeyBase64 := "MIGJAoGBAJJYXgBem1scLKPEjwKrW8+ci3B/YNN3aY2DJ3lc5e2wNc0SmFikDpow1TdYcKl2wdrXX7sMRsyjTk15IECMezyHzaJGQ9TinnkQixJ+YnlNdLC04TNWOg13plyahIXBforYAjYl2wVIA8Yma2bEQFhmAFkEX1A/Q1dIKy6EfQ+xAgMBAAE="
    
        // Base64 decode.
        publicKeyBinary, err := base64.StdEncoding.DecodeString(publicKeyBase64)
        if err != nil {
            panic(err)
        }
    
        // rsa.PublicKey is a big.Int (N: modulus) and an integer (E: exponent).
        var pubKey rsa.PublicKey
        if rest, err := asn1.Unmarshal(publicKeyBinary, &pubKey); err != nil {
            panic(err)
        } else if len(rest) != 0 {
            panic("rest is not nil")
        }
    
        fmt.Printf("key: %+v
    ", pubKey)
    }
    

    This prints out:

    key: {N:+102767083290202280873554060983826675083148443795791447833515664566475334389364583758312108980110921996262487865832851258326049062353432991986398760705560379825908169063986770245967781444794847106351934016144540466696422397564949226710181429429140226472206572796987719088983654589217713611861345869296293449649 E:65537}

    You can now use your public key in package rsa functions.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示