@Override public byte[] encrypt(final byte[] bytes) throws EncryptionError { if (inUse.getAndSet(true)) { // our copy is in use synchronized (copyMutex) { if (copy == null) copy = new PublicKey(pack()); } return copy.encrypt(bytes); } else { try { return publicKey.encrypt(bytes); } finally { inUse.set(false); } } }
/** * Get all addresses, used by this role. For public keys returns addresses too. * @deprecated the only usable check allowance method is isAllowedForKeys * @return list of strings with addresses */ @Deprecated public List<String> getAllAddresses() { List<String> res = new ArrayList<>(); getKeyAddresses().forEach(ka -> res.add(ka.toString())); getKeys().forEach(publicKey -> res.add(publicKey.getShortAddress().toString())); return res; }
private boolean hasAllKeys(SimpleRole role1, SimpleRole role2) { if(!role1.keyRecords.keySet().stream().allMatch(k-> role2.keyRecords.containsKey(k) || role2.keyAddresses.contains(k.getShortAddress()) || role2.keyAddresses.contains(k.getLongAddress()) || role2.anonymousIds.contains(new AnonymousId(k.createAnonymousId())))) return false; if(!role1.keyAddresses.stream().allMatch(ka-> role2.keyAddresses.contains(ka) || role2.keyRecords.keySet().stream().anyMatch(key->ka.equals(key.getShortAddress()) || ka.equals(key.getLongAddress())))) return false; if(!role1.anonymousIds.stream().allMatch(anonymousId -> role2.anonymousIds.contains(anonymousId) || role2.keyRecords.keySet().stream().anyMatch(key->new AnonymousId(key.createAnonymousId()).equals(anonymousId)))) return false; return true; }
/** * Unpack the remote public key, check if it is trusted, if the {@link #remoteKey} is null, saves new value, * otherwise checks that it is the same key, or throws {@link IllegalArgumentException}. * <p> * Set the remote key and accurately check that it was not spoofed, e.g. only one key could be set event several * times. Because of the p2p nature of the connection we have no guarantee which way the remote key will arrive * first (in the "hello" command from the remote or from the hello answer from the remote), this method allows to * set the remote key in right mode. * * @param packedKey packed remoteKey * * @throws IllegalArgumentException if the {@link #remoteKey} is already set to a different key. */ public void setRemoteKey(@NonNull byte[] packedKey) throws EncryptionError { if (isTrustedKey != null && !isTrustedKey.test(packedKey)) throw new IllegalArgumentException("public key is not accepted"); PublicKey rk = new PublicKey(packedKey); synchronized (ready) { if (remoteKey == null) remoteKey = rk; else if (!rk.equals(remoteKey)) throw new IllegalArgumentException("remote key already set to a different value"); } }
/** * We have received {@link PacketTypes#NACK} packet. Means that session is broken, e.g. remote node was * rebooted. Need to restart handshake procedure immediately. * @param packet received {@link Packet} */ private void onReceiveNack(Packet packet) throws EncryptionError, SymmetricKey.AuthenticationFailed { report(logLabel, ()->"received nack from " + packet.senderNodeId, VerboseLevel.BASE); Session session = getOrCreateSession(packet.senderNodeId); if (session != null) { if (session.state.get() == Session.STATE_EXCHANGING) { List dataList = Boss.load(packet.payload); byte[] data = ((Bytes)dataList.get(0)).toArray(); byte[] sign = ((Bytes)dataList.get(1)).toArray(); if (new PublicKey(session.remoteNodeInfo.getPublicKey().pack()).verify(data, sign, HashType.SHA512)) { List nackPacketIdList = Boss.load(data); Integer nackPacketId = (int)nackPacketIdList.get(0); if (session.retransmitMap.containsKey(nackPacketId)) { session.startHandshake(); restartHandshakeIfNeeded(session, Instant.now()); } } } } }
public PublicKey bin2publicKey(byte[] binary) throws EncryptionError { return new PublicKey(binary); }
byte[] remoteNonce = ((Bytes)packetData.get(0)).toArray(); byte[] packetSign = ((Bytes)packetData.get(1)).toArray(); if (new PublicKey(session.remoteNodeInfo.getPublicKey().pack()).verify(remoteNonce, packetSign, HashType.SHA512)) { session.removeHandshakePacketsFromRetransmitMap(); session.remoteNonce = remoteNonce; List data = Arrays.asList(session.localNonce, session.remoteNonce); byte[] packed = Boss.pack(data); byte[] encrypted = new PublicKey(session.remoteNodeInfo.getPublicKey().pack()).encrypt(packed); byte[] sign = new PrivateKey(ownPrivateKey.pack()).sign(encrypted, HashType.SHA512);
@Override public Binder serialize(Object object, BiSerializer serializer) { return Binder.of("packed", serializer.serialize(((PublicKey) object).pack())); }
@Test public void getAllAddresses() throws Exception { Contract contract = new Contract(TestKeys.privateKey(0)); ListRole owner = new ListRole("owner"); owner.addRole(new SimpleRole("owner", Arrays.asList(TestKeys.publicKey(0), TestKeys.publicKey(1)))); owner.addRole(new SimpleRole("owner", Arrays.asList(TestKeys.publicKey(2).getLongAddress()))); owner.addRole(new SimpleRole("owner", Arrays.asList(TestKeys.publicKey(3).getShortAddress(), TestKeys.publicKey(4)))); contract.registerRole(owner); List<String> addresses = contract.getRole("owner").getAllAddresses(); System.out.println("owner: " + addresses); for (String addr : addresses) assertThat(addr, Matchers.anyOf( Matchers.equalTo(TestKeys.publicKey(0).getShortAddress().toString()), Matchers.equalTo(TestKeys.publicKey(1).getShortAddress().toString()), Matchers.equalTo(TestKeys.publicKey(2).getLongAddress().toString()), Matchers.equalTo(TestKeys.publicKey(3).getShortAddress().toString()), Matchers.equalTo(TestKeys.publicKey(4).getShortAddress().toString()) )); }
@Test public void testListRoleCheckAll() throws Exception { KeyAddress k0 = TestKeys.publicKey(0).getShortAddress(); KeyAddress k1 = TestKeys.publicKey(1).getLongAddress(); KeyAddress k2 = TestKeys.publicKey(2).getShortAddress(); KeyAddress k3 = TestKeys.publicKey(3).getLongAddress(); String p0 = TestKeys.publicKey(0).packToBase64String(); String p1 = TestKeys.publicKey(1).packToBase64String(); String p2 = TestKeys.publicKey(2).packToBase64String(); String p3 = TestKeys.publicKey(3).packToBase64String(); Contract contract = new Contract(TestKeys.privateKey(0)); String js = "";
@Test public void testSimpleRoleCheck() throws Exception { KeyAddress k0 = TestKeys.publicKey(0).getShortAddress(); KeyAddress k1 = TestKeys.publicKey(1).getShortAddress(); KeyAddress k2 = TestKeys.publicKey(2).getShortAddress(); String p0 = TestKeys.publicKey(0).packToBase64String(); String p1 = TestKeys.publicKey(1).packToBase64String(); String p2 = TestKeys.publicKey(2).packToBase64String(); Contract contract = new Contract(TestKeys.privateKey(0)); String js = ""; js += "print('testSimpleRoleCheck');"; js += "var simpleRole = jsApi.getRoleBuilder().createSimpleRole('owner', '"+k0.toString()+"', '"+k1.toString()+"', '"+k2.toString()+"');"; js += "var check0 = simpleRole.isAllowedForKeys(jsApi.base64toPublicKey('"+p0+"'), jsApi.base64toPublicKey('"+p1+"'));"; js += "var check1 = simpleRole.isAllowedForKeys(jsApi.base64toPublicKey('"+p0+"'), jsApi.base64toPublicKey('"+p1+"'), jsApi.base64toPublicKey('"+p2+"'));"; js += "print('check0: ' + check0);"; js += "print('check1: ' + check1);"; js += "result = [check0, check1];"; JSApiScriptParameters scriptParameters = new JSApiScriptParameters(); contract.getDefinition().setJS(js.getBytes(), "client script.js", scriptParameters); contract.seal(); ScriptObjectMirror res = (ScriptObjectMirror)contract.execJS(js.getBytes()); assertFalse((boolean)res.get("0")); assertTrue((boolean)res.get("1")); }
@Test public void serializationTest() throws Exception { byte[] packedPublicKey = Do.decodeBase64(publicKey64); PublicKey publicKey = new PublicKey(packedPublicKey); byte[] packedPublicKey2 = publicKey.pack(); assertArrayEquals(packedPublicKey, packedPublicKey2); byte[] packedPrivateKey = Do.decodeBase64(TestKeys.binaryKeys[3]); PrivateKey privateKey = new PrivateKey(packedPrivateKey); byte[] packedPrivateKey2 = privateKey.pack(); assertArrayEquals(packedPrivateKey, packedPrivateKey2); }
private Object onHello(Binder params) throws IOException { // Checking protocol and version if (!params.getStringOrThrow("protocol").equals("bitrusted")) throw new IOException("unsupported protocol, needs bitrusted'"); if (params.getIntOrThrow("version") > MY_VERSION) throw new IOException("unsupported protocol version, needs <= " + MY_VERSION); // checking parameters byte[] nonce = params.getBinaryOrThrow("nonce"); setRemoteKey(params.getBinaryOrThrow("public_key")); remoteSessionKey = new SymmetricKey(params.getBinaryOrThrow("session_key")); // We intentionally do not use capsule here to improve network speed byte[] result = Boss.pack(Binder.fromKeysValues( "session_key", mySessionKey.pack(), "nonce", nonce) ); result = remoteKey.encrypt(result); byte[] signature = myKey.sign(result, HashType.SHA256); ready.fire(null); // log.d(toString() + " returning hello"); return Binder.fromKeysValues( "data", result, "signature", signature, "public_key", myKey.getPublicKey().pack() ); }
@Test public void testKeys() throws Exception { // Test vectors are for key #1 PrivateKey key = (PrivateKey) TestKeys.privateKey(1); byte[] encrypted = Bytes.fromBase64(encrypted64).toArray(); byte[] decrypted = key.decrypt(encrypted); assertEquals(plainText, new String(decrypted)); PublicKey publicKey = key.getPublicKey(); byte[] encrypted2 = publicKey.encrypt(plainText); assertEquals(plainText, new String(key.decrypt(encrypted2))); publicKey = new PublicKey(Do.decodeBase64(publicKey64)); encrypted2 = publicKey.encrypt(plainText); assertEquals(plainText, new String(key.decrypt(encrypted2))); }
boolean isSignValid = key.verify(exts, src.getBinaryOrThrow("sign"), HashType.SHA512); boolean isSign2Valid = true; byte[] sign2bin = null; isSign2Valid = key.verify(exts, sign2bin, HashType.SHA3_384); if (isSignValid && isSign2Valid) { Binder b = Boss.unpack(exts); try { byte[] publicKeyBytes = b.getBinaryOrThrow("pub_key"); es.publicKey = new PublicKey(publicKeyBytes); } catch (IllegalArgumentException e) { es.publicKey = null;
@Override public KeyInfo info() { if (keyInfo == null) { KeyInfo i = getPublicKey().info(); keyInfo = new KeyInfo(KeyInfo.Algorythm.RSAPrivate, i.getTag(), privateKey .getBitStrength() / 8); } return super.info(); }
public byte[] encrypt(String plainText) throws EncryptionError { return encrypt(plainText.getBytes(Ut.utf8)); }