title: Generate a VAPID keys in Java and pass them to JavaScript PushManager
body: <p>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 <code>applicationServerKey</code>. </p>
  
  <p>The PushManager <code>subscribe</code> method takes a VAPID key (public key alone) as a parameter and will give a subscription end point and keys to push messages.</p>
  
  <p>To generate VAPID keys, I have been using node.js (google <code>web-push</code> package) and <code>openssl</code> till now. But in my use case VAPID keys should be generated within Java and passed to JavaScript to subscribe from the browser. </p>
  
  <p>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 <code>subscribe</code> method returns an error saying: </p>
  
  <blockquote>
    <p>Unable to register service worker. DOMException: Failed to execute
    'subscribe' on 'PushManager': The provided applicationServerKey is not
    valid..</p>
  </blockquote>
  
  <p>Please help me resolve this issue. Below is my Java code:</p>
  
  <pre class="lang-java prettyprint-override"><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()));
  </code></pre>