org.bouncycastle.jce.spec.ECNamedCurveParameterSpec Java Examples

The following examples show how to use org.bouncycastle.jce.spec.ECNamedCurveParameterSpec. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SoftKeymasterBlob.java    From keystore-decryptor with Apache License 2.0 7 votes vote down vote up
private static ECPrivateKey toJcaPrivateKey(org.bouncycastle.asn1.sec.ECPrivateKey ecPrivateKey)
        throws GeneralSecurityException {
    String curveName = null;
    ASN1ObjectIdentifier curveId = (ASN1ObjectIdentifier) ecPrivateKey.getParameters();
    if (curveId.equals(secp224r1_OID)) {
        curveName = "secp224r1";
    } else if (curveId.equals(prime256v1_OID)) {
        curveName = "prime256v1";
    } else if (curveId.equals(secp384r1_OID)) {
        curveName = "secp384r1";
    } else if (curveId.equals(secp521r1_OID)) {
        curveName = "secp521r1";
    } else {
        throw new IllegalStateException("Unknown curve OID: " + curveId);
    }

    ECNamedCurveParameterSpec sp = ECNamedCurveTable.getParameterSpec(curveName);
    ECParameterSpec params = new ECNamedCurveSpec(sp.getName(), sp.getCurve(), sp.getG(),
            sp.getN(), sp.getH());

    ECPrivateKeySpec pkSpec = new ECPrivateKeySpec(ecPrivateKey.getKey(), params);
    KeyFactory kf = KeyFactory.getInstance("EC");
    ECPrivateKey privateKey = (ECPrivateKey) kf.generatePrivate(pkSpec);

    return privateKey;
}
 
Example #2
Source File: HdPrivateKey.java    From ontology-java-sdk with GNU Lesser General Public License v3.0 6 votes vote down vote up
public HdPublicKey getHdPublicKey() throws Exception {
    ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec((String) new Object[]{Curve.P256.toString()}[0]);
    ECPoint Q = spec.getG().multiply(new BigInteger(1, getPrivateKey())).normalize();
    if (Q == null || Q.getAffineXCoord() == null || Q.getAffineYCoord() == null) {
        throw new SDKException(ErrorCode.OtherError("normalize error"));
    }
    return new HdPublicKey(new HdKey.Builder()
            .network(hdKey.getNetwork())
            .neutered(true)
            .key(Q.getEncoded(true))
            .parentFingerprint(hdKey.getParentFingerprint())
            .depth(hdKey.depth())
            .childNumber(hdKey.getChildNumber())
            .chainCode(hdKey.getChainCode())
            .build());
}
 
Example #3
Source File: WeEventFileClient.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
public void genPemFile(String filePath) throws BrokerException {
    validateLocalFile(filePath);
    try {
        BouncyCastleProvider prov = new BouncyCastleProvider();
        Security.addProvider(prov);

        ECNamedCurveParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec(CURVE_TYPE);
        KeyPairGenerator generator = KeyPairGenerator.getInstance(ALGORITHM, prov.getName());
        generator.initialize(ecSpec, new SecureRandom());
        KeyPair pair = generator.generateKeyPair();
        String pubKey = pair.getPublic().toString();
        String account = HEX_HEADER + pubKey.substring(pubKey.indexOf("[") + 1, pubKey.indexOf("]")).replace(":", "");

        PemFile privatePemFile = new PemFile(pair.getPrivate(), PRIVATE_KEY_DESC);
        PemFile publicPemFile = new PemFile(pair.getPublic(), PUBLIC_KEY_DESC);


        System.out.println(filePath + PATH_SEPARATOR + account + PRIVATE_KEY_SUFFIX);
        privatePemFile.write(filePath + PATH_SEPARATOR + account + PRIVATE_KEY_SUFFIX);
        publicPemFile.write(filePath + PATH_SEPARATOR + account + PUBLIC_KEY_SUFFIX);
    } catch (IOException | NoSuchProviderException | NoSuchAlgorithmException | InvalidAlgorithmParameterException e) {
        log.error("generate pem file error");
        throw new BrokerException(ErrorCode.FILE_GEN_PEM_BC_FAILED);
    }
}
 
Example #4
Source File: KeyCodec.java    From UAF with Apache License 2.0 6 votes vote down vote up
/**
 * Decode based on X, Y 32 byte integers
 * 
 * @param pubKey
 * @param curveName
 *            - Example secp256r1
 * @return
 * @throws InvalidKeySpecException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 */
public static PublicKey getPubKeyFromCurve(byte[] pubKey, String curveName)
		throws InvalidKeySpecException, NoSuchAlgorithmException,
		NoSuchProviderException {

	ECNamedCurveParameterSpec spec = ECNamedCurveTable
			.getParameterSpec(curveName);
	KeyFactory kf = KeyFactory.getInstance("ECDSA",
			new BouncyCastleProvider());
	ECNamedCurveSpec params = new ECNamedCurveSpec(curveName,
			spec.getCurve(), spec.getG(), spec.getN());
	ECPoint point = ECPointUtil.decodePoint(params.getCurve(), pubKey);
	ECPublicKeySpec pubKeySpec = new ECPublicKeySpec(point, params);
	ECPublicKey pk = (ECPublicKey) kf.generatePublic(pubKeySpec);
	return pk;
}
 
Example #5
Source File: LocalIdentity.java    From ts3j with Apache License 2.0 6 votes vote down vote up
/**
 * Generates a new identity with a given security level target.
 * @param securityLevel security level to generate for (may take time)
 * @return local identity with given security level
 * @throws GeneralSecurityException
 */
public static LocalIdentity generateNew(int securityLevel) throws GeneralSecurityException {
    ECNamedCurveParameterSpec ecp = ECNamedCurveTable.getParameterSpec("prime256v1");
    ECDomainParameters domainParams =
            new ECDomainParameters(ecp.getCurve(), ecp.getG(), ecp.getN(), ecp.getH(), ecp.getSeed());
    ECKeyGenerationParameters keyGenParams = new ECKeyGenerationParameters(domainParams, new SecureRandom());

    ECKeyPairGenerator generator = new ECKeyPairGenerator();
    generator.init(keyGenParams);

    AsymmetricCipherKeyPair keyPair = generator.generateKeyPair();
    ECPrivateKeyParameters privateKey = (ECPrivateKeyParameters) keyPair.getPrivate();
    ECPublicKeyParameters publicKey = (ECPublicKeyParameters) keyPair.getPublic();

    LocalIdentity localIdentity = load(publicKey.getQ().normalize(), privateKey.getD());
    localIdentity.improveSecurity(securityLevel);

    return localIdentity;
}
 
Example #6
Source File: NotificationService.java    From org.openhab.ui.habot with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Generate an EC keypair on the prime256v1 curve and save them to a file for later usage.
 *
 * Some code borrowed from
 * <a href=
 * "https://github.com/web-push-libs/webpush-java/blob/master/src/main/java/nl/martijndwars/webpush/cli/handlers/GenerateKeyHandler.java">webpush-java</a>.
 *
 * @author Martijn Dwars
 *
 * @throws InvalidAlgorithmParameterException
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws IOException
 * @throws FileNotFoundException
 */
private void generateVAPIDKeyPair() throws InvalidAlgorithmParameterException, NoSuchProviderException,
        NoSuchAlgorithmException, FileNotFoundException, IOException {
    ECNamedCurveParameterSpec parameterSpec = ECNamedCurveTable.getParameterSpec(Utils.CURVE);

    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(Utils.ALGORITHM, PROVIDER_NAME);
    keyPairGenerator.initialize(parameterSpec);

    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    byte[] publicKey = Utils.savePublicKey((ECPublicKey) keyPair.getPublic());
    byte[] privateKey = Utils.savePrivateKey((ECPrivateKey) keyPair.getPrivate());

    List<String> encodedKeys = new ArrayList<String>();
    encodedKeys.add(BaseEncoding.base64Url().encode(publicKey));
    encodedKeys.add(BaseEncoding.base64Url().encode(privateKey));

    // write the public key, then the private key in encoded form on separate lines in the file
    File file = new File(ConfigConstants.getUserDataFolder() + File.separator + VAPID_KEYS_FILE_NAME);
    file.getParentFile().mkdirs();
    IOUtils.writeLines(encodedKeys, System.lineSeparator(), new FileOutputStream(file));

    this.publicVAPIDKey = encodedKeys.get(0);
    this.privateVAPIDKey = encodedKeys.get(1);
}
 
Example #7
Source File: PushService.java    From org.openhab.ui.habot with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Encrypt the getPayload using the user's public key using Elliptic Curve
 * Diffie Hellman cryptography over the prime256v1 curve.
 *
 * @return An Encrypted object containing the public key, salt, and
 *         ciphertext, which can be sent to the other party.
 */
public static Encrypted encrypt(byte[] buffer, PublicKey userPublicKey, byte[] userAuth, int padSize)
        throws GeneralSecurityException, IOException {
    ECNamedCurveParameterSpec parameterSpec = ECNamedCurveTable.getParameterSpec("prime256v1");

    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("ECDH", "BC");
    keyPairGenerator.initialize(parameterSpec);

    KeyPair serverKey = keyPairGenerator.generateKeyPair();

    Map<String, KeyPair> keys = new HashMap<>();
    keys.put("server-key-id", serverKey);

    Map<String, String> labels = new HashMap<>();
    labels.put("server-key-id", "P-256");

    byte[] salt = new byte[16];
    SECURE_RANDOM.nextBytes(salt);

    HttpEce httpEce = new HttpEce(keys, labels);
    byte[] ciphertext = httpEce.encrypt(buffer, salt, null, "server-key-id", userPublicKey, userAuth, padSize);

    return new Encrypted.Builder().withSalt(salt).withPublicKey(serverKey.getPublic()).withCiphertext(ciphertext)
            .build();
}
 
Example #8
Source File: JWKParser.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private PublicKey createECPublicKey() {
    String crv = (String) jwk.getOtherClaims().get(ECPublicJWK.CRV);
    BigInteger x = new BigInteger(1, Base64Url.decode((String) jwk.getOtherClaims().get(ECPublicJWK.X)));
    BigInteger y = new BigInteger(1, Base64Url.decode((String) jwk.getOtherClaims().get(ECPublicJWK.Y)));

    String name;
    switch (crv) {
        case "P-256" :
            name = "secp256r1";
            break;
        case "P-384" :
            name = "secp384r1";
            break;
        case "P-521" :
            name = "secp521r1";
            break;
        default :
            throw new RuntimeException("Unsupported curve");
    }

    try {
        ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec(name);
        ECNamedCurveSpec params = new ECNamedCurveSpec("prime256v1", spec.getCurve(), spec.getG(), spec.getN());
        ECPoint point = new ECPoint(x, y);
        ECPublicKeySpec pubKeySpec = new ECPublicKeySpec(point, params);

        KeyFactory kf = KeyFactory.getInstance("ECDSA");
        return kf.generatePublic(pubKeySpec);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #9
Source File: KeyUtils.java    From aerogear-unifiedpush-server with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the base64 encoded public key as a PublicKey object
 */
public static PublicKey getUserPublicKey(WebPushRegistration registration) throws NoSuchAlgorithmException, InvalidKeySpecException {

    KeyFactory kf = KeyFactory.getInstance("ECDH", PROVIDER);
    ECNamedCurveParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("secp256r1");
    ECPoint point = ecSpec.getCurve().decodePoint(registration.getKeyAsBytes());
    ECPublicKeySpec pubSpec = new ECPublicKeySpec(point, ecSpec);

    return kf.generatePublic(pubSpec);
}
 
Example #10
Source File: KeyCodec.java    From UAF with Apache License 2.0 5 votes vote down vote up
/**
 * Decode based on d - 32 byte integer
 * 
 * @param privKey
 * @param curveName
 *            - Example secp256r1
 * @return
 * @throws InvalidKeySpecException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 */
public static PrivateKey getPrivKeyFromCurve(byte[] privKey,
		String curveName) throws InvalidKeySpecException,
		NoSuchAlgorithmException, NoSuchProviderException {

	ECNamedCurveParameterSpec spec = ECNamedCurveTable
			.getParameterSpec(curveName);
	KeyFactory kf = KeyFactory.getInstance("ECDSA",
			new BouncyCastleProvider());
	ECNamedCurveSpec params = new ECNamedCurveSpec(curveName,
			spec.getCurve(), spec.getG(), spec.getN());
	ECPrivateKeySpec priKey = new ECPrivateKeySpec(new BigInteger(privKey), // d
			params);
	return kf.generatePrivate(priKey);
}
 
Example #11
Source File: ECPRIVATE.java    From warp10-platform with Apache License 2.0 5 votes vote down vote up
@Override
public Object apply(WarpScriptStack stack) throws WarpScriptException {
  
  Object top = stack.pop();
  
  if (!(top instanceof Map)) {
    throw new WarpScriptException(getName() + " expects a parameter map.");
  }
  
  Map<Object,Object> params = (Map<Object,Object>) top;
  
  String name = String.valueOf(params.get(Constants.KEY_CURVE));
  
  final ECNamedCurveParameterSpec curve = ECNamedCurveTable.getParameterSpec(name);
  
  if (null == curve) {
    throw new WarpScriptException(getName() + " curve name not in " + ECGEN.getCurves() + ".");
  }

  if (!(params.get(Constants.KEY_D) instanceof String)) {
    throw new WarpScriptException(getName() + " missing or non-String parameter '" + Constants.KEY_D + "'.");
  }

  final BigInteger d = new BigInteger((String) params.get(Constants.KEY_D));
  
  ECPrivateKey privateKey = new ECPrivateKey() {
    public String getFormat() { return "PKCS#8"; }
    public byte[] getEncoded() { return null; }
    public String getAlgorithm() { return "EC"; }
    public ECParameterSpec getParameters() { return curve; }
    public BigInteger getD() { return d; }
  };
    
  stack.push(privateKey);
  
  return stack;
}
 
Example #12
Source File: ECPUBLIC.java    From warp10-platform with Apache License 2.0 5 votes vote down vote up
@Override
public Object apply(WarpScriptStack stack) throws WarpScriptException {
  
  Object top = stack.pop();
  
  if (!(top instanceof Map)) {
    throw new WarpScriptException(getName() + " expects a parameter map.");
  }
  
  Map<Object,Object> params = (Map<Object,Object>) top;
  
  String name = String.valueOf(params.get(Constants.KEY_CURVE));
  
  final ECNamedCurveParameterSpec curve = ECNamedCurveTable.getParameterSpec(name);

  if (null == curve) {
    throw new WarpScriptException(getName() + " curve name not in " + ECGEN.getCurves() + ".");
  }
  
  if (!(params.get(Constants.KEY_Q) instanceof String)) {
    throw new WarpScriptException(getName() + " missing or non-String parameter '" + Constants.KEY_Q + "'.");
  }
  
  final byte[] encoded = Hex.decode((String) params.get(Constants.KEY_Q));
  
  final ECPoint q = curve.getCurve().decodePoint(encoded);
      
  ECPublicKey publicKey = new ECPublicKey() {
    public String getFormat() { return "PKCS#8"; }
    public byte[] getEncoded() { return encoded; }
    public String getAlgorithm() { return "EC"; }
    public ECParameterSpec getParameters() { return curve; }
    public ECPoint getQ() { return q; }
  };
    
  stack.push(publicKey);
  
  return stack;
}
 
Example #13
Source File: Utils.java    From webpush-java with MIT License 5 votes vote down vote up
/**
 * Verify that the private key belongs to the public key.
 *
 * @param privateKey
 * @param publicKey
 * @return
 */
public static boolean verifyKeyPair(PrivateKey privateKey, PublicKey publicKey) {
    ECNamedCurveParameterSpec curveParameters = ECNamedCurveTable.getParameterSpec(CURVE);
    ECPoint g = curveParameters.getG();
    ECPoint sG = g.multiply(((java.security.interfaces.ECPrivateKey) privateKey).getS());

    return sG.equals(((ECPublicKey) publicKey).getQ());
}
 
Example #14
Source File: GenerateKeyHandler.java    From webpush-java with MIT License 5 votes vote down vote up
/**
 * Generate an EC keypair on the prime256v1 curve.
 *
 * @return
 * @throws InvalidAlgorithmParameterException
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 */
public KeyPair generateKeyPair() throws InvalidAlgorithmParameterException, NoSuchProviderException, NoSuchAlgorithmException {
    ECNamedCurveParameterSpec parameterSpec = ECNamedCurveTable.getParameterSpec(CURVE);

    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM, PROVIDER_NAME);
    keyPairGenerator.initialize(parameterSpec);

    return keyPairGenerator.generateKeyPair();
}
 
Example #15
Source File: Crypto.java    From webauthndemo with Apache License 2.0 5 votes vote down vote up
public static PublicKey getECPublicKey(java.security.spec.ECPoint w, String stdCurveName)
    throws NoSuchAlgorithmException, InvalidKeySpecException {
  ECNamedCurveParameterSpec parameterSpec = ECNamedCurveTable.getParameterSpec(stdCurveName);
  java.security.spec.ECParameterSpec params = new ECNamedCurveSpec(parameterSpec.getName(),
      parameterSpec.getCurve(), parameterSpec.getG(), parameterSpec.getN(), parameterSpec.getH(),
      parameterSpec.getSeed());
  KeySpec keySpec = new java.security.spec.ECPublicKeySpec(w, params);
  KeyFactory keyFactory = KeyFactory.getInstance("EC");
  return keyFactory.generatePublic(keySpec);
}
 
Example #16
Source File: Utils.java    From org.openhab.ui.habot with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Load the private key from a URL-safe base64 encoded string
 *
 * @param encodedPrivateKey
 * @return
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
public static PrivateKey loadPrivateKey(String encodedPrivateKey)
        throws NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException {
    byte[] decodedPrivateKey = base64Decode(encodedPrivateKey);
    BigInteger s = BigIntegers.fromUnsignedByteArray(decodedPrivateKey);
    ECNamedCurveParameterSpec parameterSpec = ECNamedCurveTable.getParameterSpec(CURVE);
    ECPrivateKeySpec privateKeySpec = new ECPrivateKeySpec(s, parameterSpec);
    KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM, PROVIDER_NAME);

    return keyFactory.generatePrivate(privateKeySpec);
}
 
Example #17
Source File: PushService.java    From org.openhab.ui.habot with Eclipse Public License 1.0 5 votes vote down vote up
private boolean verifyKeyPair() {
    ECNamedCurveParameterSpec curveParameters = ECNamedCurveTable.getParameterSpec(Utils.CURVE);
    ECPoint g = curveParameters.getG();
    ECPoint sG = g.multiply(((ECPrivateKey) privateKey).getS());

    return sG.equals(((ECPublicKey) publicKey).getQ());
}
 
Example #18
Source File: TrustAddressGenerator.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
private static ECPublicKey decodeKey(byte[] encoded)
        throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException {
    ECNamedCurveParameterSpec params = ECNamedCurveTable.getParameterSpec("secp256k1");
    KeyFactory fact = KeyFactory.getInstance("ECDSA", "BC");
    ECCurve curve = params.getCurve();
    java.security.spec.EllipticCurve ellipticCurve = EC5Util.convertCurve(curve, params.getSeed());
    java.security.spec.ECPoint point = ECPointUtil.decodePoint(ellipticCurve, encoded);
    java.security.spec.ECParameterSpec params2 = EC5Util.convertSpec(ellipticCurve, params);
    java.security.spec.ECPublicKeySpec keySpec = new java.security.spec.ECPublicKeySpec(point, params2);
    return (ECPublicKey) fact.generatePublic(keySpec);
}
 
Example #19
Source File: ECDSAAlgorithm.java    From md_blockchain with Apache License 2.0 5 votes vote down vote up
public static String decodePublicKey(String encodePubKeyBase64String) {
    try {
        byte[] encodePubkeyBytes = Base64.decodeBase64(encodePubKeyBase64String);
        ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec("secp256k1");
        ECPoint pointQ = spec.getG().getCurve().decodePoint(encodePubkeyBytes);
        String result = Base64.encodeBase64String(pointQ.getEncoded(false));
        result = result.replaceAll("[\\s*\t\n\r]", "");
        return result;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #20
Source File: ECDSAAlgorithm.java    From md_blockchain with Apache License 2.0 5 votes vote down vote up
/**
 * 生成公钥,encode为true时为短公钥
 * @param privateKeyBase64String
 * 私钥
 * @param encode
 * 是否使用base64缩短
 * @return
 * 公钥
 */
public static String generatePublicKey(String privateKeyBase64String, boolean encode) {
    try {
        byte[] privateKeyBytes = Base64.decodeBase64(privateKeyBase64String);
        ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec("secp256k1");
        ECPoint pointQ = spec.getG().multiply(new BigInteger(1, privateKeyBytes));
        String result = Base64.encodeBase64String(pointQ.getEncoded(encode));
        result = result.replaceAll("[\\s*\t\n\r]", "");
        return result;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #21
Source File: EcCurveBc.java    From protect with MIT License 5 votes vote down vote up
/**
 * Constructs a EcCurveBc from an ECParameterSpec
 * 
 * Extends EcCurve which supports additional methods
 * 
 * @see EcCurve
 * 
 * @param parameterSpec
 */
public EcCurveBc(final ECNamedCurveParameterSpec parameterSpec) {

	super(parameterSpec.getCurve().getA().toBigInteger(), parameterSpec.getCurve().getB().toBigInteger(),
			parameterSpec.getCurve().getField().getCharacteristic(), parameterSpec.getN(),
			parameterSpec.getG().getAffineXCoord().toBigInteger(),
			parameterSpec.getG().getAffineYCoord().toBigInteger());

	this.parameterSpec = parameterSpec;

}
 
Example #22
Source File: Account.java    From ontology-java-sdk with GNU Lesser General Public License v3.0 5 votes vote down vote up
public Account(byte[] prikey, SignatureScheme scheme) throws Exception {
    Security.addProvider(new BouncyCastleProvider());
    signatureScheme = scheme;

    if (scheme == SignatureScheme.SM3WITHSM2) {
        this.keyType = KeyType.SM2;
        this.curveParams = new Object[]{Curve.SM2P256V1.toString()};
    } else if (scheme == SignatureScheme.SHA256WITHECDSA) {
        this.keyType = KeyType.ECDSA;
        this.curveParams = new Object[]{Curve.P256.toString()};
    }

    switch (scheme) {
        case SHA256WITHECDSA:
        case SM3WITHSM2:
            BigInteger d = new BigInteger(1, prikey);
            ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec((String) this.curveParams[0]);
            ECParameterSpec paramSpec = new ECNamedCurveSpec(spec.getName(), spec.getCurve(), spec.getG(), spec.getN());
            ECPrivateKeySpec priSpec = new ECPrivateKeySpec(d, paramSpec);
            KeyFactory kf = KeyFactory.getInstance("EC", "BC");
            this.privateKey = kf.generatePrivate(priSpec);

            org.bouncycastle.math.ec.ECPoint Q = spec.getG().multiply(d).normalize();
            if (Q == null || Q.getAffineXCoord() == null || Q.getAffineYCoord() == null) {
                throw new SDKException(ErrorCode.OtherError("normalize error"));
            }
            ECPublicKeySpec pubSpec = new ECPublicKeySpec(
                    new ECPoint(Q.getAffineXCoord().toBigInteger(), Q.getAffineYCoord().toBigInteger()),
                    paramSpec);
            this.publicKey = kf.generatePublic(pubSpec);
            this.addressU160 = Address.addressFromPubKey(serializePublicKey());
            break;
        default:
            throw new Exception(ErrorCode.UnsupportedKeyType);
    }
}
 
Example #23
Source File: Ts3Crypt.java    From ts3j with Apache License 2.0 4 votes vote down vote up
private static ECDomainParameters getDomainParameters() {
    ECNamedCurveParameterSpec ecp = ECNamedCurveTable.getParameterSpec("prime256v1");
    return new ECDomainParameters(ecp.getCurve(), ecp.getG(), ecp.getN(), ecp.getH(), ecp.getSeed());
}
 
Example #24
Source File: EcCurveBc.java    From protect with MIT License 4 votes vote down vote up
public static EcCurveBc createByName(final String curveName) {
	final ECNamedCurveParameterSpec parameterSpec = ECNamedCurveTable.getParameterSpec(curveName);
	return new EcCurveBc(parameterSpec);
}
 
Example #25
Source File: Account.java    From ontology-java-sdk with GNU Lesser General Public License v3.0 4 votes vote down vote up
private void parsePublicKey(byte[] data) throws Exception {
        if (data == null) {
            throw new Exception(ErrorCode.NullInput);
        }
        if (data.length < 2) {
            throw new Exception(ErrorCode.InvalidData);
        }
        if(data.length == 33){
            this.keyType = KeyType.ECDSA;
        } else if(data.length == 35) {
            this.keyType = KeyType.fromLabel(data[0]);
        }
        this.privateKey = null;
        this.publicKey = null;
        switch (this.keyType) {
            case ECDSA:
			    this.keyType = KeyType.ECDSA;
                this.curveParams = new Object[]{Curve.P256.toString()};
                ECNamedCurveParameterSpec spec0 = ECNamedCurveTable.getParameterSpec(Curve.P256.toString());
                ECParameterSpec param0 = new ECNamedCurveSpec(spec0.getName(), spec0.getCurve(), spec0.getG(), spec0.getN());
                ECPublicKeySpec pubSpec0 = new ECPublicKeySpec(
                        ECPointUtil.decodePoint(
                                param0.getCurve(),
                                Arrays.copyOfRange(data, 0, data.length)),
                        param0);
                KeyFactory kf0 = KeyFactory.getInstance("EC", "BC");
                this.publicKey = kf0.generatePublic(pubSpec0);
                break;
            case SM2:
//                this.keyType = KeyType.fromLabel(data[0]);
                Curve c = Curve.fromLabel(data[1]);
                this.curveParams = new Object[]{c.toString()};
                ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec(c.toString());
                ECParameterSpec param = new ECNamedCurveSpec(spec.getName(), spec.getCurve(), spec.getG(), spec.getN());
                ECPublicKeySpec pubSpec = new ECPublicKeySpec(
                        ECPointUtil.decodePoint(
                                param.getCurve(),
                                Arrays.copyOfRange(data, 2, data.length)),
                        param);
                KeyFactory kf = KeyFactory.getInstance("EC", "BC");
                this.publicKey = kf.generatePublic(pubSpec);
                break;
            default:
                throw new Exception(ErrorCode.UnknownKeyType);
        }
    }
 
Example #26
Source File: PushService.java    From webpush-java with MIT License 3 votes vote down vote up
/**
 * Generate the local (ephemeral) keys.
 *
 * @return
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws InvalidAlgorithmParameterException
 */
private static KeyPair generateLocalKeyPair() throws NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException {
    ECNamedCurveParameterSpec parameterSpec = ECNamedCurveTable.getParameterSpec("prime256v1");
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("ECDH", "BC");
    keyPairGenerator.initialize(parameterSpec);

    return keyPairGenerator.generateKeyPair();
}
 
Example #27
Source File: ECGEN.java    From warp10-platform with Apache License 2.0 2 votes vote down vote up
@Override
public Object apply(WarpScriptStack stack) throws WarpScriptException {
  Object top = stack.pop();

  if (!(top instanceof String)) {
    throw new WarpScriptException(getName() + " expects a curve name.");
  }

  String name = (String) top;

  ECKeyPairGenerator gen = new ECKeyPairGenerator();

  ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec(name);
  
  if (null == spec) {
    throw new WarpScriptException(getName() + " only supports the following curves: " + getCurves() + ".");
  }
  
  ECCurve curve = spec.getCurve();
  ECDomainParameters domainParams = new ECDomainParameters(curve, spec.getG(),spec.getN(), spec.getH(), spec.getSeed());    
  ECKeyGenerationParameters params = new ECKeyGenerationParameters(domainParams, CryptoHelper.getSecureRandom());
  
  gen.init(params);

  final AsymmetricCipherKeyPair keypair = gen.generateKeyPair();

  ECPrivateKeyParameters privateKey = (ECPrivateKeyParameters) keypair.getPrivate();
  ECPublicKeyParameters publicKey = (ECPublicKeyParameters) keypair.getPublic();
  
  Map<String,String> keyparams = new HashMap<String,String>();
  
  keyparams.put(Constants.KEY_CURVE, name);
  keyparams.put(Constants.KEY_D, privateKey.getD().toString());
  
  stack.push(keyparams);
  
  keyparams = new HashMap<String,String>();

  keyparams.put(Constants.KEY_CURVE, name);
  keyparams.put(Constants.KEY_Q, Hex.encodeHexString(publicKey.getQ().getEncoded()));

  stack.push(keyparams);

  return stack;
}