org.bouncycastle.jce.ECNamedCurveTable Java Examples

The following examples show how to use org.bouncycastle.jce.ECNamedCurveTable. 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: DynamoDBSignerTest.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setUpClass() throws Exception {

    //RSA key generation
    KeyPairGenerator rsaGen = KeyPairGenerator.getInstance("RSA");
    rsaGen.initialize(2048, Utils.getRng());
    KeyPair sigPair = rsaGen.generateKeyPair();
    pubKeyRsa = sigPair.getPublic();
    privKeyRsa = sigPair.getPrivate();

    KeyGenerator macGen = KeyGenerator.getInstance("HmacSHA256");
    macGen.init(256, Utils.getRng());
    macKey = macGen.generateKey();

    Security.addProvider(new BouncyCastleProvider());
    ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("secp384r1");
    KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", "BC");
    g.initialize(ecSpec, Utils.getRng());
    KeyPair keypair = g.generateKeyPair();
    pubKeyEcdsa = keypair.getPublic();
    privKeyEcdsa = keypair.getPrivate();

}
 
Example #3
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 #4
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 #5
Source File: Keys.java    From blockchain with Apache License 2.0 6 votes vote down vote up
/**
 * Create a keypair using SECP-256k1 curve.
 *
 * <p>Private keypairs are encoded using PKCS8
 *
 * <p>Private keys are encoded using X.509
 */
static KeyPair createSecp256k1KeyPair() throws NoSuchProviderException,
        NoSuchAlgorithmException, InvalidAlgorithmParameterException {

    // 注册 BC Provider
    Security.addProvider(new BouncyCastleProvider());
    // 创建椭圆曲线算法的密钥对生成器
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(
            CryptoConstants.KEY_GEN_ALGORITHM,
            BouncyCastleProvider
            .PROVIDER_NAME);
    // 椭圆曲线(EC)域参数设定
    ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec(CryptoConstants.EC_PARAM_SPEC);
    keyPairGenerator.initialize(ecSpec, new SecureRandom());
    return keyPairGenerator.generateKeyPair();
}
 
Example #6
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 #7
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 #8
Source File: DynamoDbSignerTest.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setUpClass() throws Exception {
    
    //RSA key generation
    KeyPairGenerator rsaGen = KeyPairGenerator.getInstance("RSA");
    rsaGen.initialize(2048, Utils.getRng());
    KeyPair sigPair = rsaGen.generateKeyPair();
    pubKeyRsa = sigPair.getPublic();
    privKeyRsa = sigPair.getPrivate();
    
    KeyGenerator macGen = KeyGenerator.getInstance("HmacSHA256");
    macGen.init(256, Utils.getRng());
    macKey = macGen.generateKey();
    
    Security.addProvider(new BouncyCastleProvider());
    ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("secp384r1");
    KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", "BC");
    g.initialize(ecSpec, Utils.getRng());
    KeyPair keypair = g.generateKeyPair();
    pubKeyEcdsa = keypair.getPublic();
    privKeyEcdsa = keypair.getPrivate();
    
}
 
Example #9
Source File: KeycardTest.java    From status-keycard with Apache License 2.0 6 votes vote down vote up
private void verifySignResp(byte[] data, APDUResponse response) throws Exception {
  Signature signature = Signature.getInstance("SHA256withECDSA", "BC");
  assertEquals(0x9000, response.getSw());
  byte[] sig = response.getData();
  byte[] keyData = extractPublicKeyFromSignature(sig);
  sig = extractSignature(sig);

  ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("secp256k1");
  ECPublicKeySpec cardKeySpec = new ECPublicKeySpec(ecSpec.getCurve().decodePoint(keyData), ecSpec);
  ECPublicKey cardKey = (ECPublicKey) KeyFactory.getInstance("ECDSA", "BC").generatePublic(cardKeySpec);

  signature.initVerify(cardKey);
  assertEquals((SecureChannel.SC_KEY_LENGTH * 2 / 8) + 1, keyData.length);
  signature.update(data);
  assertTrue(signature.verify(sig));
  assertFalse(isMalleable(sig));
}
 
Example #10
Source File: EOSFormatter.java    From eosio-java with MIT License 6 votes vote down vote up
/**
 * Decompresses a public key based on the algorithm used to generate it.
 *
 * @param compressedPublicKey Compressed public key as byte[]
 * @param algorithmEmployed Algorithm used during key creation
 * @return Decompressed public key as byte[]
 * @throws EOSFormatterError when public key decompression fails.
 */
@NotNull
private static byte[] decompressPublickey(byte[] compressedPublicKey,
        AlgorithmEmployed algorithmEmployed)
        throws EOSFormatterError {
    try {
        ECParameterSpec parameterSpec = ECNamedCurveTable
                .getParameterSpec(algorithmEmployed.getString());
        ECPoint ecPoint = parameterSpec.getCurve().decodePoint(compressedPublicKey);
        byte[] x = ecPoint.getXCoord().getEncoded();
        byte[] y = ecPoint.getYCoord().getEncoded();
        if (y.length > STANDARD_KEY_LENGTH) {
            y = Arrays.copyOfRange(y, 1, y.length);
        }
        return Bytes.concat(new byte[]{UNCOMPRESSED_PUBLIC_KEY_BYTE_INDICATOR}, x, y);
    } catch (Exception e) {
        throw new EOSFormatterError(ErrorConstants.PUBLIC_KEY_DECOMPRESSION_ERROR, e);
    }
}
 
Example #11
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 #12
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 #13
Source File: Utils.java    From webpush-java with MIT License 5 votes vote down vote up
/**
 * Load a public key from the private key.
 *
 * @param privateKey
 * @return
 */
public static ECPublicKey loadPublicKey(ECPrivateKey privateKey) throws NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException {
    KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM, PROVIDER_NAME);
    ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec(CURVE);
    ECPoint Q = ecSpec.getG().multiply(privateKey.getD());
    byte[] publicDerBytes = Q.getEncoded(false);
    ECPoint point = ecSpec.getCurve().decodePoint(publicDerBytes);
    ECPublicKeySpec pubSpec = new ECPublicKeySpec(point, ecSpec);

    return (ECPublicKey) keyFactory.generatePublic(pubSpec);
}
 
Example #14
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 #15
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 #16
Source File: Utils.java    From webpush-java with MIT License 5 votes vote down vote up
/**
 * Load the public key from a byte array. 
 *
 * @param decodedPublicKey
 */
public static PublicKey loadPublicKey(byte[] decodedPublicKey) throws NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException {
    KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM, PROVIDER_NAME);
    ECParameterSpec parameterSpec = ECNamedCurveTable.getParameterSpec(CURVE);
    ECCurve curve = parameterSpec.getCurve();
    ECPoint point = curve.decodePoint(decodedPublicKey);
    ECPublicKeySpec pubSpec = new ECPublicKeySpec(point, parameterSpec);

    return keyFactory.generatePublic(pubSpec);
}
 
Example #17
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 #18
Source File: ECGEN.java    From warp10-platform with Apache License 2.0 5 votes vote down vote up
public static String getCurves() {
  StringBuilder sb = new StringBuilder();
  Enumeration<String> names = ECNamedCurveTable.getNames();
  while (names.hasMoreElements()) {
    if (sb.length() > 0) {
      sb.append(", ");
    }
    sb.append(names.nextElement());
  }
  return sb.toString();
}
 
Example #19
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 #20
Source File: KeycardTest.java    From status-keycard with Apache License 2.0 5 votes vote down vote up
private KeyPairGenerator keypairGenerator() throws Exception {
  ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("secp256k1");
  KeyPairGenerator g = KeyPairGenerator.getInstance("ECDH", "BC");
  g.initialize(ecSpec);

  return g;
}
 
Example #21
Source File: BouncyCastleLib.java    From ECTester with MIT License 5 votes vote down vote up
@Override
public Set<String> getCurves() {
    Set<String> result = new TreeSet<>();
    Enumeration names = ECNamedCurveTable.getNames();
    while (names.hasMoreElements()) {
        result.add((String) names.nextElement());
    }
    return result;
}
 
Example #22
Source File: KeyCodec.java    From UAF with Apache License 2.0 5 votes vote down vote up
public static KeyPair generate() throws NoSuchAlgorithmException,
		InvalidAlgorithmParameterException {
	SecureRandom random = new SecureRandom();
	ECParameterSpec ecSpec = ECNamedCurveTable
			.getParameterSpec("secp256r1");
	KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA");
	g.initialize(ecSpec, random);
	return g.generateKeyPair();
}
 
Example #23
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 #24
Source File: DynamoDBEncryptorTest.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
private EncryptionMaterialsProvider getMaterialProviderwithECDSA()
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, NoSuchProviderException {
    Security.addProvider(new BouncyCastleProvider());
    ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("secp384r1");
    KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", "BC");
    g.initialize(ecSpec, Utils.getRng());
    KeyPair keypair = g.generateKeyPair();
    Map<String, String> description = new HashMap<String, String>();
    description.put(DynamoDBEncryptor.DEFAULT_SIGNING_ALGORITHM_HEADER, "SHA384withECDSA");
    return new SymmetricStaticProvider(null, keypair, description);
}
 
Example #25
Source File: DynamoDbEncryptorTest.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
private EncryptionMaterialsProvider getMaterialProviderwithECDSA() 
       throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, NoSuchProviderException {
        Security.addProvider(new BouncyCastleProvider());
        ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("secp384r1");
        KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", "BC");
        g.initialize(ecSpec, Utils.getRng());
        KeyPair keypair = g.generateKeyPair();
        Map<String, String> description = new HashMap<>();
        description.put(DynamoDbEncryptor.DEFAULT_SIGNING_ALGORITHM_HEADER, "SHA384withECDSA");
        return new SymmetricStaticProvider(null, keypair, description);
}
 
Example #26
Source File: KeyUtils.java    From aerogear-unifiedpush-server with Apache License 2.0 5 votes vote down vote up
public static PrivateKey loadPrivateKey(String privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
    byte[] decodedPrivateKey = Base64Encoder.decode(privateKey);
    BigInteger s = BigIntegers.fromUnsignedByteArray(decodedPrivateKey);
    ECParameterSpec parameterSpec = ECNamedCurveTable.getParameterSpec(CURVE);
    ECPrivateKeySpec privateKeySpec = new ECPrivateKeySpec(s, parameterSpec);
    KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM, PROVIDER);

    return keyFactory.generatePrivate(privateKeySpec);
}
 
Example #27
Source File: KeyUtils.java    From aerogear-unifiedpush-server with Apache License 2.0 5 votes vote down vote up
public static PublicKey loadPublicKey(String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
    byte[] decodedPublicKey = Base64Encoder.decode(publicKey);
    KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM, PROVIDER);
    ECParameterSpec parameterSpec = ECNamedCurveTable.getParameterSpec(CURVE);
    ECCurve curve = parameterSpec.getCurve();
    ECPoint point = curve.decodePoint(decodedPublicKey);
    ECPublicKeySpec pubSpec = new ECPublicKeySpec(point, parameterSpec);

    return keyFactory.generatePublic(pubSpec);

}
 
Example #28
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 #29
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 #30
Source File: Utils.java    From org.openhab.ui.habot with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Load the public key from a URL-safe base64 encoded string. Takes into
 * account the different encodings, including point compression.
 *
 * @param encodedPublicKey
 */
public static PublicKey loadPublicKey(String encodedPublicKey)
        throws NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException {
    byte[] decodedPublicKey = base64Decode(encodedPublicKey);
    KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM, PROVIDER_NAME);
    ECParameterSpec parameterSpec = ECNamedCurveTable.getParameterSpec(CURVE);
    ECCurve curve = parameterSpec.getCurve();
    ECPoint point = curve.decodePoint(decodedPublicKey);
    ECPublicKeySpec pubSpec = new ECPublicKeySpec(point, parameterSpec);

    return keyFactory.generatePublic(pubSpec);
}