Java加載原始的64字節(jié)長(zhǎng)的ECDSA公鑰到ECPublicKey對(duì)象中

先解釋一下物臂,HyperLedger 超級(jí)賬本的公私鑰組成笛丙,私鑰隨機(jī)生成,然后私鑰通過secp256r1算法推導(dǎo)公鑰价说。
java 8以后版本中辆亏,包含關(guān)于EC公鑰的實(shí)現(xiàn)。
原始十六進(jìn)制公鑰是由 前綴 04 + public.x + public.y組成鳖目,大小是65扮叨,不加04是64字節(jié)。順便提一下领迈,私鑰長(zhǎng)度是32字節(jié)彻磁。
取得x 和y數(shù)組的辦法如下:

  ECPublicKey ecPublicKey = (ECPublicKey) publicKey;

  // Get x coordinate
  byte[] x = ecPublicKey.getW().getAffineX().toByteArray();
  if (x[0] == 0)
    x = Arrays.copyOfRange(x, 1, x.length);
  // Get Y coordinate
  byte[] y = ecPublicKey.getW().getAffineY().toByteArray();
  if (y[0] == 0)
    y = Arrays.copyOfRange(y, 1, y.length);

Java 7 is required for the EC functionality and Java 8 for the Base 64 encoder / decoder, no additional libraries - just plain Java. Note that this will actually display the public key as a named curve when printed out, something most other solutions won't do. If you have an up-to-date runtime, this other answer is more clean.

This answer is going to be tough if we do this using ECPublicKeySpec. So lets cheat a bit and use X509EncodedKeySpec instead:

private static byte[] P256_HEAD = Base64.getDecoder().decode("MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE");

/**
 * Converts an uncompressed secp256r1 / P-256 public point to the EC public key it is representing.
 * @param w a 64 byte uncompressed EC point consisting of just a 256-bit X and Y
 * @return an <code>ECPublicKey</code> that the point represents 
 */
public static ECPublicKey generateP256PublicKeyFromFlatW(byte[] w) throws InvalidKeySpecException {
    byte[] encodedKey = new byte[P256_HEAD.length + w.length];
    System.arraycopy(P256_HEAD, 0, encodedKey, 0, P256_HEAD.length);
    System.arraycopy(w, 0, encodedKey, P256_HEAD.length, w.length);
    KeyFactory eckf;
    try {
        eckf = KeyFactory.getInstance("EC");
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException("EC key factory not present in runtime");
    }
    X509EncodedKeySpec ecpks = new X509EncodedKeySpec(encodedKey);
    return (ECPublicKey) eckf.generatePublic(ecpks);
}

Usage:

ECPublicKey key = generateP256PublicKeyFromFlatW(w);
System.out.println(key);

The idea behind this is to create a temporary X509 encoded key, which happily ends with the public point w at the end. The bytes before that contain the ASN.1 DER encoding of the OID of the named curve and structural overhead, ending with byte 04 indicating an uncompressed point. Here is an example what the structure looks like, using value 1 and 2 for the 32-byte X and Y.

The 32-byte X and Y values of the uncompressed point values removed to create the header. This only works because the point is statically sized - it's location at the end is only determined by the size of the curve.

Now all that is required in the function generateP256PublicKeyFromFlatW is to add the received public point w to the header and run it through the decoder implemented for X509EncodedKeySpec.


The above code uses a raw, uncompressed public EC point - just a 32 byte X and Y - without the uncompressed point indicator with value 04. Of course it is easy to support 65 byte compressed points as well:

/**
 * Converts an uncompressed secp256r1 / P-256 public point to the EC public key it is representing.
 * @param w a 64 byte uncompressed EC point starting with <code>04</code>
 * @return an <code>ECPublicKey</code> that the point represents 
 */
public static ECPublicKey generateP256PublicKeyFromUncompressedW(byte[] w) throws InvalidKeySpecException {
    if (w[0] != 0x04) {
        throw new InvalidKeySpecException("w is not an uncompressed key");
    }
    return generateP256PublicKeyFromFlatW(Arrays.copyOfRange(w, 1, w.length));
}

Finally, I generated the constant P256_HEAD head value in base 64 using:

private static byte[] createHeadForNamedCurve(String name, int size)
        throws NoSuchAlgorithmException,
        InvalidAlgorithmParameterException, IOException {
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC");
    ECGenParameterSpec m = new ECGenParameterSpec(name);
    kpg.initialize(m);
    KeyPair kp = kpg.generateKeyPair();
    byte[] encoded = kp.getPublic().getEncoded();
    return Arrays.copyOf(encoded, encoded.length - 2 * (size / Byte.SIZE));
}

called by:

String name = "NIST P-256";
int size = 256;
byte[] head = createHeadForNamedCurve(name, size);
System.out.println(Base64.getEncoder().encodeToString(head));
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市狸捅,隨后出現(xiàn)的幾起案子衷蜓,更是在濱河造成了極大的恐慌,老刑警劉巖尘喝,帶你破解...
    沈念sama閱讀 218,941評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件磁浇,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡朽褪,警方通過查閱死者的電腦和手機(jī)置吓,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,397評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來缔赠,“玉大人衍锚,你說我怎么就攤上這事∴脱撸” “怎么了戴质?”我有些...
    開封第一講書人閱讀 165,345評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)梁棠。 經(jīng)常有香客問我置森,道長(zhǎng)斗埂,這世上最難降的妖魔是什么符糊? 我笑而不...
    開封第一講書人閱讀 58,851評(píng)論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮呛凶,結(jié)果婚禮上男娄,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好模闲,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,868評(píng)論 6 392
  • 文/花漫 我一把揭開白布建瘫。 她就那樣靜靜地躺著,像睡著了一般尸折。 火紅的嫁衣襯著肌膚如雪啰脚。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,688評(píng)論 1 305
  • 那天实夹,我揣著相機(jī)與錄音橄浓,去河邊找鬼。 笑死亮航,一個(gè)胖子當(dāng)著我的面吹牛荸实,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播缴淋,決...
    沈念sama閱讀 40,414評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼准给,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了重抖?” 一聲冷哼從身側(cè)響起露氮,我...
    開封第一講書人閱讀 39,319評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎仇哆,沒想到半個(gè)月后沦辙,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,775評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡讹剔,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,945評(píng)論 3 336
  • 正文 我和宋清朗相戀三年油讯,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片延欠。...
    茶點(diǎn)故事閱讀 40,096評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡陌兑,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出由捎,到底是詐尸還是另有隱情兔综,我是刑警寧澤,帶...
    沈念sama閱讀 35,789評(píng)論 5 346
  • 正文 年R本政府宣布狞玛,位于F島的核電站软驰,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏心肪。R本人自食惡果不足惜锭亏,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,437評(píng)論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望硬鞍。 院中可真熱鬧慧瘤,春花似錦戴已、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,993評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至怔匣,卻和暖如春握联,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背每瞒。 一陣腳步聲響...
    開封第一講書人閱讀 33,107評(píng)論 1 271
  • 我被黑心中介騙來泰國(guó)打工拴疤, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人独泞。 一個(gè)月前我還...
    沈念sama閱讀 48,308評(píng)論 3 372
  • 正文 我出身青樓呐矾,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親懦砂。 傳聞我的和親對(duì)象是個(gè)殘疾皇子蜒犯,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,037評(píng)論 2 355