开发者

Sending public key to Android from Ruby

开发者 https://www.devze.com 2023-03-29 18:50 出处:网络
On the server OpenSSL::PKey::RSA.generate(1024).public_key.to_s returns \"-----BEGIN RSA PUBLIC KEY-----\\nMIGJAoGBAPHpKZe0jKkyyslkhnoQzRovzQB+6OLtACNkILk+6UKgYJ1UM7Qkpxab\\noEHnpR/XHrIfFUB8dfhaI

On the server

OpenSSL::PKey::RSA.generate(1024).public_key.to_s

returns

"-----BEGIN RSA PUBLIC KEY-----\nMIGJAoGBAPHpKZe0jKkyyslkhnoQzRovzQB+6OLtACNkILk+6UKgYJ1UM7Qkpxab\noEHnpR/XHrIfFUB8dfhaIeqHGC3IASZh6vveH6ypwZTqDHrejqYcfOuKOJcCRDJf\n/qxeVy1jwt7oMbrDhCeVNd3eIYdq0joEnZ6k4KwqvG1ZIOKkE8adAgMBAAE=\n-----END RSA PUBLIC KEY-----\n"

which works when I copy and paste this string as a java String. However, I need to get this public key through a httpResp开发者_开发知识库onse. When called by an HttpRequest, it returns:

-----BEGIN RSA PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCySmMxjxX1Xw80yRB35BQHP27V
EhIUG9/bxsyJMs4rhmvnpP7saeBznyDMQ3I5wt7cJEPABy+QuuAGjphj6/FsfsXP
9zLRroX02f48fQXNM7j8RtQ5y8bhcZrnb8/MNoAKnbAqkKlkuW/gRxSB0qeG5Q17
vvSJ6KHb5heAFwaGtwIDAQAB
-----END RSA PUBLIC KEY-----

But this is invalid. What gives?


This is really a nice one :) OK, let's start from the beginning.

  • I checked whether I can Base64-decode the contents of the string with problems -> yes
  • I checked whether the decoded byte array is a valid DER encoding -> yes
  • I checked whether the DER encoding represents an RSA public key -> yes
  • I checked whether I could parse the original string as an RSA public key directly -> no

WTF?! Then I reencoded the RSA public key I was able to decode to PEM - and it gave me:

-----BEGIN PUBLIC KEY-----
... same Base64 as in your string ...
-----END PUBLIC KEY-----

See the difference - it's the PEM headers. The structure that is Base64-encoded is the generic X.509 representation of a public key (therefore also the difference in the headers), and not the RSA-specific representation described in PKCS#1, which your headers would imply! If you change the PEM headers, then it'll work!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号