|
| 1 | +// Copyright 2018 The NATS Authors |
| 2 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 | +// you may not use this file except in compliance with the License. |
| 4 | +// You may obtain a copy of the License at: |
| 5 | +// |
| 6 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 | +// |
| 8 | +// Unless required by applicable law or agreed to in writing, software |
| 9 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 | +// See the License for the specific language governing permissions and |
| 12 | +// limitations under the License. |
| 13 | + |
| 14 | +package io.nats.examples; |
| 15 | + |
| 16 | +import java.io.BufferedReader; |
| 17 | +import java.io.File; |
| 18 | +import java.io.FileReader; |
| 19 | +import java.io.IOException; |
| 20 | +import java.security.GeneralSecurityException; |
| 21 | + |
| 22 | +import io.nats.client.AuthHandler; |
| 23 | +import io.nats.client.NKey; |
| 24 | + |
| 25 | +public class ExampleAuthHandler implements AuthHandler { |
| 26 | + private NKey nkey; |
| 27 | + |
| 28 | + public ExampleAuthHandler(String path) throws Exception { |
| 29 | + BufferedReader in = null; |
| 30 | + |
| 31 | + try { |
| 32 | + in = new BufferedReader((new FileReader(new File(path)))); |
| 33 | + |
| 34 | + char[] buffer = new char[2048]; |
| 35 | + int len = in.read(buffer); |
| 36 | + char[] seed = new char[len]; |
| 37 | + |
| 38 | + System.arraycopy(buffer, 0, seed, 0, len); |
| 39 | + |
| 40 | + this.nkey = NKey.fromSeed(seed); |
| 41 | + |
| 42 | + for (int i=0;i<buffer.length;i++) { |
| 43 | + buffer[i] = '\0'; |
| 44 | + } |
| 45 | + } finally { |
| 46 | + if (in != null) { |
| 47 | + in.close(); |
| 48 | + } |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + public NKey getNKey() { |
| 53 | + return this.nkey; |
| 54 | + } |
| 55 | + |
| 56 | + public char[] getID() { |
| 57 | + try { |
| 58 | + return this.nkey.getPublicKey(); |
| 59 | + } catch (GeneralSecurityException|IOException|NullPointerException ex) { |
| 60 | + return null; |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + public byte[] sign(byte[] nonce) { |
| 65 | + try { |
| 66 | + return this.nkey.sign(nonce); |
| 67 | + } catch (GeneralSecurityException|IOException|NullPointerException ex) { |
| 68 | + return null; |
| 69 | + } |
| 70 | + } |
| 71 | +} |
0 commit comments