I’m trying to use web push notifications with the web push protocol in my app. In order to use the Push API with VAPID I need an applicationServerKey
.
The PushManager subscribe
method takes a VAPID key (public key alone) as a parameter and will give a subscription end point and keys to push messages.
To generate VAPID keys, I have been using node.js (google web-push
package) and openssl
till now. But in my use case VAPID keys should be generated within Java and passed to JavaScript to subscribe from the browser.
I am trying with the code below in Java to generate VAPID keys. I am able to create keys successfully but when I pass the generated public key (base64-encoded string), the subscribe
method returns an error saying:
Unable to register service worker. DOMException: Failed to execute 'subscribe' on 'PushManager': The provided applicationServerKey is not valid..
Please help me resolve this issue. Below is my Java code:
ECNamedCurveParameterSpec parameterSpec =
ECNamedCurveTable.getParameterSpec("prime256v1");
KeyPairGenerator keyPairGenerator =
KeyPairGenerator.getInstance("ECDH", "BC");
keyPairGenerator.initialize(parameterSpec);
KeyPair serverKey = keyPairGenerator.generateKeyPair();
PrivateKey priv = serverKey.getPrivate();
PublicKey pub = serverKey.getPublic();`
System.out.println(Base64.toBase64String(pub.getEncoded()));
With bountycastle you can generate vapid keys with this code :