Java Code Examples for org.bouncycastle.jce.ECNamedCurveTable#getParameterSpec()
The following examples show how to use
org.bouncycastle.jce.ECNamedCurveTable#getParameterSpec() .
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 |
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 |
@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: WeEventFileClient.java From WeEvent with Apache License 2.0 | 6 votes |
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: HdPrivateKey.java From ontology-java-sdk with GNU Lesser General Public License v3.0 | 6 votes |
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 5
Source File: NotificationService.java From org.openhab.ui.habot with Eclipse Public License 1.0 | 6 votes |
/** * 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 6
Source File: KeycardTest.java From status-keycard with Apache License 2.0 | 6 votes |
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 7
Source File: LocalIdentity.java From ts3j with Apache License 2.0 | 6 votes |
/** * 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 8
Source File: KeyCodec.java From UAF with Apache License 2.0 | 6 votes |
/** * 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 9
Source File: ECPUBLIC.java From warp10-platform with Apache License 2.0 | 5 votes |
@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 10
Source File: Utils.java From webpush-java with MIT License | 5 votes |
/** * 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 11
Source File: GenerateKeyHandler.java From webpush-java with MIT License | 5 votes |
/** * 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 12
Source File: ECPRIVATE.java From warp10-platform with Apache License 2.0 | 5 votes |
@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 13
Source File: KeyUtils.java From aerogear-unifiedpush-server with Apache License 2.0 | 5 votes |
/** * 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 14
Source File: TrustAddressGenerator.java From alpha-wallet-android with MIT License | 5 votes |
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 15
Source File: KeycardTest.java From status-keycard with Apache License 2.0 | 5 votes |
private KeyPairGenerator keypairGenerator() throws Exception { ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("secp256k1"); KeyPairGenerator g = KeyPairGenerator.getInstance("ECDH", "BC"); g.initialize(ecSpec); return g; }
Example 16
Source File: KeycardTest.java From status-keycard with Apache License 2.0 | 5 votes |
private void verifyKeyDerivation(KeyPair keyPair, byte[] chainCode, int[] path) throws Exception { byte[] hash = sha256(new byte[8]); APDUResponse resp = cmdSet.sign(hash); assertEquals(0x9000, resp.getSw()); byte[] sig = resp.getData(); byte[] publicKey = extractPublicKeyFromSignature(sig); sig = extractSignature(sig); if (cmdSet.getApplicationInfo().hasKeyManagementCapability()) { DeterministicKey key = deriveKey(keyPair, chainCode, path); assertTrue(key.verify(hash, sig)); assertArrayEquals(key.getPubKeyPoint().getEncoded(false), publicKey); } else { Signature signature = Signature.getInstance("SHA256withECDSA", "BC"); ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("secp256k1"); ECPublicKeySpec cardKeySpec = new ECPublicKeySpec(ecSpec.getCurve().decodePoint(publicKey), ecSpec); ECPublicKey cardKey = (ECPublicKey) KeyFactory.getInstance("ECDSA", "BC").generatePublic(cardKeySpec); signature.initVerify(cardKey); signature.update(new byte[8]); assertTrue(signature.verify(sig)); } resp = cmdSet.getStatus(KeycardApplet.GET_STATUS_P1_KEY_PATH); assertEquals(0x9000, resp.getSw()); byte[] rawPath = resp.getData(); assertEquals(path.length * 4, rawPath.length); for (int i = 0; i < path.length; i++) { int k = path[i]; int k1 = (rawPath[i * 4] << 24) | (rawPath[(i * 4) + 1] << 16) | (rawPath[(i * 4) + 2] << 8) | rawPath[(i * 4) + 3]; assertEquals(k, k1); } }
Example 17
Source File: Account.java From ontology-java-sdk with GNU Lesser General Public License v3.0 | 5 votes |
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 18
Source File: EcCurveBc.java From protect with MIT License | 4 votes |
public EcCurveBc(ECParameterSpec params) { super(params); this.parameterSpec = ECNamedCurveTable.getParameterSpec(this.getName()); }
Example 19
Source File: EcCurveBc.java From protect with MIT License | 4 votes |
public static EcCurveBc createByName(final String curveName) { final ECNamedCurveParameterSpec parameterSpec = ECNamedCurveTable.getParameterSpec(curveName); return new EcCurveBc(parameterSpec); }
Example 20
Source File: ECDSAKeyFactory.java From oxAuth with MIT License | 4 votes |
public ECDSAKeyFactory(SignatureAlgorithm signatureAlgorithm, String dnName) throws InvalidParameterException, NoSuchProviderException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, SignatureException, InvalidKeyException, CertificateEncodingException { if (signatureAlgorithm == null) { throw new InvalidParameterException("The signature algorithm cannot be null"); } this.signatureAlgorithm = signatureAlgorithm; ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec(signatureAlgorithm.getCurve().getName()); KeyPairGenerator keyGen = KeyPairGenerator.getInstance("ECDSA", "BC"); keyGen.initialize(ecSpec, new SecureRandom()); this.keyPair = keyGen.generateKeyPair(); BCECPrivateKey privateKeySpec = (BCECPrivateKey) keyPair.getPrivate(); BCECPublicKey publicKeySpec = (BCECPublicKey) keyPair.getPublic(); BigInteger x = publicKeySpec.getQ().getXCoord().toBigInteger(); BigInteger y = publicKeySpec.getQ().getYCoord().toBigInteger(); BigInteger d = privateKeySpec.getD(); this.ecdsaPrivateKey = new ECDSAPrivateKey(d); this.ecdsaPublicKey = new ECDSAPublicKey(signatureAlgorithm, x, y); if (StringUtils.isNotBlank(dnName)) { // Create certificate GregorianCalendar startDate = new GregorianCalendar(); // time from which certificate is valid GregorianCalendar expiryDate = new GregorianCalendar(); // time after which certificate is not valid expiryDate.add(Calendar.YEAR, 1); BigInteger serialNumber = new BigInteger(1024, new Random()); // serial number for certificate X509V1CertificateGenerator certGen = new X509V1CertificateGenerator(); X500Principal principal = new X500Principal(dnName); certGen.setSerialNumber(serialNumber); certGen.setIssuerDN(principal); certGen.setNotBefore(startDate.getTime()); certGen.setNotAfter(expiryDate.getTime()); certGen.setSubjectDN(principal); // note: same as issuer certGen.setPublicKey(keyPair.getPublic()); certGen.setSignatureAlgorithm("SHA256WITHECDSA"); X509Certificate x509Certificate = certGen.generate(privateKeySpec, "BC"); this.certificate = new Certificate(signatureAlgorithm, x509Certificate); } }