使用字符串类型中的私钥生成共享密钥

时间:2014-12-14 20:33:20

标签: java ssl encryption bouncycastle public-key-encryption

我对密码学知之甚少,请原谅这是一个愚蠢的问题。

我想使用Java中的私钥和对等公钥生成ECDH共享密钥。 我试图关注互联网上的一些消息来源以及这里给出的内容:http://dev.coova.org/svn/cjradius/trunk/ssl/src/main/java/net/jradius/ssl/ECDHCrypt.java

我拥有的代码,根据用户凭据生成公钥和私钥:

import com.google.bitcoin.bouncycastle.asn1.sec.SECNamedCurves;
import com.google.bitcoin.bouncycastle.asn1.x9.X9ECParameters;
import com.google.bitcoin.bouncycastle.math.ec.ECPoint;
import com.google.bitcoin.core.Utils

public String ecdaPrivate(String hexstring) {  // The hexstring is the hex value   generated based on username and password

    byte[] hexBytes = new byte[32];
    for (int i = 0, j = 0; i < hexstring.length(); i++, j++) {
        String pairStr = hexstring.substring(i, i + 2);
        int value = Integer.parseInt(pairStr, 16);
        hexBytes[j] = (byte) (value & 0xFF);

        i++;
    }

    char[] hexChars = new char[hexBytes.length * 2];
    for (int j = 0; j < hexBytes.length; j++) {
        int v = hexBytes[j] & 0xFF;
        hexChars[j * 2] = hexArray[v >>> 4];
        hexChars[j * 2 + 1] = hexArray[v & 0x0F];
    }

    return new String(hexChars);
}


public String getPublicKey(String privateKey) {
    BigInteger privKey = new BigInteger(privateKey, 16);
    X9ECParameters ecp = SECNamedCurves.getByName("secp256k1");
    ECPoint curvePt = ecp.getG().multiply(privKey);
    BigInteger x = curvePt.getX().toBigInteger();
    BigInteger y = curvePt.getY().toBigInteger();
    byte[] xBytes = this.removeSignByte(x.toByteArray());
    byte[] yBytes = this.removeSignByte(y.toByteArray());
    byte[] pubKeyBytes = new byte[65];
    pubKeyBytes[0] = new Byte("04");
    System.arraycopy(xBytes, 0, pubKeyBytes, 1, xBytes.length);
    System.arraycopy(yBytes, 0, pubKeyBytes, 33, yBytes.length);
    return this.bytesToHex(pubKeyBytes);
}

这些键是String类型。 问题是来自Internet的大多数源使用Privatekey和PublicKey类型(java.security.PrivateKey),但是我所拥有的私钥是字符串类型的形式。 问题是如何将字符串转换为私钥/公钥对象类型。

0 个答案:

没有答案