You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@plc4x.apache.org by hu...@apache.org on 2021/01/30 12:23:28 UTC

[plc4x] 03/03: Working on encryption

This is an automated email from the ASF dual-hosted git repository.

hutcheb pushed a commit to branch feature/native_opua_client
in repository https://gitbox.apache.org/repos/asf/plc4x.git

commit b7767cfb7cc1c8a19ee177a3c1e5ba92498a4ce0
Author: hutcheb <be...@gmail.com>
AuthorDate: Sat Jan 30 07:22:35 2021 -0500

    Working on encryption
---
 .../resources/templates/java/data-io-template.ftlh |  10 +-
 .../main/resources/templates/java/io-template.ftlh |  11 +
 .../knxnetip/readwrite/model/KnxDatapoint.go       |  20 +-
 .../java/opcua/config/OpcuaConfiguration.java      |   5 +-
 .../java/opcua/context/CertificateKeyPair.java     |   8 +-
 .../java/opcua/protocol/OpcuaProtocolLogic.java    | 499 ++++++++++++++++-----
 .../resources/protocols/knxnetip/knxnetip.mspec    |   2 +-
 protocols/knxnetip/src/main/xslt/knx-types.xsl     |  16 +-
 .../src/main/resources/protocols/opcua/opcua.mspec |   8 +-
 protocols/opcua/src/main/xslt/opc-types.xsl        |   4 +-
 10 files changed, 433 insertions(+), 150 deletions(-)

diff --git a/build-utils/language-java/src/main/resources/templates/java/data-io-template.ftlh b/build-utils/language-java/src/main/resources/templates/java/data-io-template.ftlh
index a384f6e..3c423fb 100644
--- a/build-utils/language-java/src/main/resources/templates/java/data-io-template.ftlh
+++ b/build-utils/language-java/src/main/resources/templates/java/data-io-template.ftlh
@@ -91,6 +91,7 @@ public class ${type.name}IO {
         <#assign defaultCaseOutput=false>
         <#list type.switchField.cases as case><#if case.discriminatorValues?has_content>if(<#list case.discriminatorValues as discriminatorValue>EvaluationHelper.equals(${helper.toParseExpression(null, type.switchField.discriminatorExpressions[discriminatorValue?index], type.parserArguments)}, <#if helper.discriminatorValueNeedsStringEqualityCheck(type.switchField.discriminatorExpressions[discriminatorValue?index])>"${discriminatorValue}"<#else>${discriminatorValue}</#if>)<#sep> && </#se [...]
             <#assign valueDefined=false>
+
             <#list case.fields as field>
                 <#switch field.typeName>
                     <#case "array">
@@ -114,6 +115,7 @@ public class ${type.name}IO {
                     ${field.name}.add(new ${helper.getPlcValueTypeForTypeReference(field.type)}((${helper.getNonPrimitiveLanguageTypeNameForField(field)}) <#if helper.isSimpleTypeReference(field.type)>${helper.getReadBufferReadMethodCall(field.type)})<#else>${field.type.name}IO.staticParse(io<#if field.params?has_content>, <#list field.params as parserArgument>(${helper.getLanguageTypeNameForTypeReference(helper.getArgumentType(field.type, parserArgument?index), true)}) (${helper.toParse [...]
                 }
             }
+            LOGGER.info("${field.name} - {}", ${field.name});
             <#-- In all other cases do we have to work with a list, that is later converted to an array -->
                         <#else>
             <#-- For a length array, we read data till the read position of the buffer reaches a given position -->
@@ -162,6 +164,7 @@ public class ${type.name}IO {
             if(${field.name} != ${type.name}.${field.name?upper_case}) {
                 throw new ParseException("Expected constant value " + ${type.name}.${field.name?upper_case} + " but got " + ${field.name});
             }
+            LOGGER.info("${field.name} - {}", ${field.name});
                         <#if field.name == "value">
                             <#assign valueDefined=true>
                         </#if>
@@ -170,6 +173,7 @@ public class ${type.name}IO {
 
             // Enum field (${field.name})
             ${helper.getNonPrimitiveLanguageTypeNameForField(field)} ${field.name} = ${helper.getNonPrimitiveLanguageTypeNameForField(field)}.enumForValue(${helper.getReadBufferReadMethodCall(helper.getEnumBaseTypeReference(field.type))});
+            LOGGER.info("${field.name} - {}", ${field.name});
                         <#if field.name == "value">
                             <#assign valueDefined=true>
                         </#if>
@@ -178,6 +182,7 @@ public class ${type.name}IO {
 
             // Manual Field (${field.name})
             ${helper.getLanguageTypeNameForField(field)} ${field.name} = (${helper.getLanguageTypeNameForField(field)}) (${helper.toParseExpression(field, field.parseExpression, type.parserArguments)});
+            LOGGER.info("${field.name} - {}", ${field.name});
                         <#if field.name == "value">
                             <#assign valueDefined=true>
                         </#if>
@@ -197,9 +202,11 @@ public class ${type.name}IO {
                         <#if helper.isEnumField(field)>
             // Enum field (${field.name})
             ${helper.getNonPrimitiveLanguageTypeNameForField(field)} ${field.name} = ${helper.getNonPrimitiveLanguageTypeNameForField(field)}.enumForValue(${helper.getReadBufferReadMethodCall(helper.getEnumBaseTypeReference(field.type))});
+            LOGGER.info("${field.name} - {}", ${field.name});
                         <#else>
             // Simple Field (${field.name})
             ${helper.getNonPrimitiveLanguageTypeNameForField(field)} ${field.name} = <#if helper.isSimpleTypeReference(field.type)>${helper.getReadBufferReadMethodCall(field.type)}<#else>${field.type.name}IO.staticParse(io<#if field.params?has_content>, <#list field.params as parserArgument>(${helper.getLanguageTypeNameForTypeReference(helper.getArgumentType(field.type, parserArgument?index), true)}) (${helper.toParseExpression(field, parserArgument, type.parserArguments)})<#sep>, </#sep [...]
+            LOGGER.info("${field.name} - {}", ${field.name});
                         </#if>
                         <#if case.name == "Struct" || ((case.name == "DATE_AND_TIME") && ((field.name == "year") || (field.name == "month") || (field.name == "day") || (field.name == "hour") || (field.name == "minutes") || (field.name == "seconds"))) || ((case.name == "DATE") && ((field.name == "year") || (field.name == "month") || (field.name == "day"))) || ((case.name == "TIME_OF_DAY") && ((field.name == "hour") || (field.name == "minutes") || (field.name == "seconds"))) || field.name  [...]
                             <#assign valueDefined=true>
@@ -261,7 +268,8 @@ public class ${type.name}IO {
                 <#assign valueDefined=true>
             </#if>
 
-            <#if valueDefined>
+
+        <#if valueDefined>
                 <#switch case.name>
                     <#case "TIME">
             return new PlcTIME(value);
diff --git a/build-utils/language-java/src/main/resources/templates/java/io-template.ftlh b/build-utils/language-java/src/main/resources/templates/java/io-template.ftlh
index ea54624..2514145 100644
--- a/build-utils/language-java/src/main/resources/templates/java/io-template.ftlh
+++ b/build-utils/language-java/src/main/resources/templates/java/io-template.ftlh
@@ -172,6 +172,8 @@ public class ${type.name}IO implements <#if outputFlavor != "passive">MessageIO<
                 ${arrayField.name}[curItem] = <#if helper.isSimpleTypeReference(arrayField.type)><#assign simpleTypeReference = arrayField.type>${helper.getReadBufferReadMethodCall(simpleTypeReference)}<#else>${arrayField.type.name}IO.staticParse(io<#if field.params?has_content>, <#list field.params as parserArgument>(${helper.getLanguageTypeNameForTypeReference(helper.getArgumentType(arrayField.type, parserArgument?index), true)}) (${helper.toParseExpression(arrayField, parserArgument,  [...]
             }
         }
+            LOGGER.info("${arrayField.name} - {}", ${arrayField.name});
+
         <#-- In all other cases do we have to work with a list, that is later converted to an array -->
         <#else>
             <#-- For a length array, we read data till the read position of the buffer reaches a given position -->
@@ -229,6 +231,7 @@ public class ${type.name}IO implements <#if outputFlavor != "passive">MessageIO<
             if(checksum != checksumRef) {
                 throw new ParseException(String.format("Checksum verification failed. Expected %04X but got %04X", checksumRef & 0xFFFF, checksum & 0xFFFF));
             }
+            LOGGER.info("CheckSum - {}", checksum);
         }
         <#break>
     <#case "const">
@@ -240,6 +243,8 @@ public class ${type.name}IO implements <#if outputFlavor != "passive">MessageIO<
         if(${constField.name} != ${type.name}.${constField.name?upper_case}) {
             throw new ParseException("Expected constant value " + ${type.name}.${constField.name?upper_case} + " but got " + ${constField.name});
         }
+    LOGGER.info("${constField.name} - {}", ${constField.name});
+
         <#break>
     <#case "discriminator">
         <#assign discriminatorField = field>
@@ -250,12 +255,14 @@ public class ${type.name}IO implements <#if outputFlavor != "passive">MessageIO<
         <#else>
             ${helper.getLanguageTypeNameForField(field)} ${discriminatorField.name} = <#if helper.isSimpleTypeReference(discriminatorField.type)>${helper.getReadBufferReadMethodCall(discriminatorField.type)}<#else>${discriminatorField.type.name}IO.staticParse(io<#if field.params?has_content>, <#list field.params as parserArgument>(${helper.getLanguageTypeNameForTypeReference(helper.getArgumentType(discriminatorField.type, parserArgument?index), true)}) (${helper.toParseExpression(discrim [...]
         </#if>
+    LOGGER.info("${discriminatorField.name} - {}", ${discriminatorField.name});
         <#break>
     <#case "enum">
         <#assign enumField = field>
 
         // Enum field (${enumField.name})
         ${helper.getLanguageTypeNameForField(field)} ${enumField.name} = ${helper.getLanguageTypeNameForField(field)}.enumForValue(${helper.getReadBufferReadMethodCall(helper.getEnumBaseTypeReference(enumField.type))});
+    LOGGER.info("${enumField.name} - {}", ${enumField.name});
         <#break>
     <#case "implicit">
         <#assign implicitField = field>
@@ -263,6 +270,7 @@ public class ${type.name}IO implements <#if outputFlavor != "passive">MessageIO<
 
         // Implicit Field (${implicitField.name}) (Used for parsing, but it's value is not stored as it's implicitly given by the objects content)
         ${helper.getLanguageTypeNameForField(field)} ${implicitField.name} = ${helper.getReadBufferReadMethodCall(simpleTypeReference)};
+    LOGGER.info("${implicitField.name} - {}", ${implicitField.name});
         <#break>
     <#case "manualArray">
         <#assign manualArrayField = field>
@@ -328,6 +336,7 @@ public class ${type.name}IO implements <#if outputFlavor != "passive">MessageIO<
 
         // Manual Field (${manualField.name})
         ${helper.getLanguageTypeNameForField(field)} ${manualField.name} = (${helper.getLanguageTypeNameForField(field)}) (${helper.toParseExpression(manualField, manualField.parseExpression, type.parserArguments)});
+    LOGGER.info("${manualField.name} - {}", ${manualField.name});
         <#break>
     <#case "optional">
         <#assign optionalField = field>
@@ -344,6 +353,7 @@ public class ${type.name}IO implements <#if outputFlavor != "passive">MessageIO<
             ${optionalField.name} = <#if helper.isSimpleTypeReference(optionalField.type)>${helper.getReadBufferReadMethodCall(optionalField.type)}<#else>${optionalField.type.name}IO.staticParse(io<#if field.params?has_content>, <#list field.params as parserArgument>(${helper.getLanguageTypeNameForTypeReference(helper.getArgumentType(optionalField.type, parserArgument?index), true)}) (${helper.toParseExpression(optionalField, parserArgument, type.parserArguments)})<#sep>, </#sep></#list> [...]
             </#if>
         }
+    LOGGER.info("${optionalField.name} - {}", ${optionalField.name});
         <#break>
     <#case "padding">
         <#assign paddingField = field>
@@ -379,6 +389,7 @@ public class ${type.name}IO implements <#if outputFlavor != "passive">MessageIO<
         <#else>
         ${helper.getLanguageTypeNameForField(simpleField)} ${simpleField.name} = <#if helper.isSimpleTypeReference(simpleField.type)><#assign simpleTypeReference = simpleField.type>${helper.getReadBufferReadMethodCall(simpleTypeReference)}<#else><#assign complexTypeReference = simpleField.type>${complexTypeReference.name}IO.staticParse(io<#if field.params?has_content>, <#list field.params as parserArgument>(${helper.getLanguageTypeNameForTypeReference(helper.getArgumentType(simpleField.t [...]
         </#if>
+    LOGGER.info("${simpleField.name} - {}", ${simpleField.name});
         <#break>
     <#case "switch">
         <#assign switchField = field>
diff --git a/plc4go/internal/plc4go/knxnetip/readwrite/model/KnxDatapoint.go b/plc4go/internal/plc4go/knxnetip/readwrite/model/KnxDatapoint.go
index 04e41e4..152ada8 100644
--- a/plc4go/internal/plc4go/knxnetip/readwrite/model/KnxDatapoint.go
+++ b/plc4go/internal/plc4go/knxnetip/readwrite/model/KnxDatapoint.go
@@ -655,7 +655,7 @@ func KnxDatapointParse(io *utils.ReadBuffer, datapointType KnxDatapointType) (ap
             }
 
             // Simple Field (value)
-            value, _valueErr := io.ReadString(8)
+            value, _valueErr := io.ReadString(-1)
             if _valueErr != nil {
                 return nil, errors.New("Error parsing 'value' field " + _valueErr.Error())
             }
@@ -668,7 +668,7 @@ func KnxDatapointParse(io *utils.ReadBuffer, datapointType KnxDatapointType) (ap
             }
 
             // Simple Field (value)
-            value, _valueErr := io.ReadString(8)
+            value, _valueErr := io.ReadString(-1)
             if _valueErr != nil {
                 return nil, errors.New("Error parsing 'value' field " + _valueErr.Error())
             }
@@ -2890,7 +2890,7 @@ func KnxDatapointParse(io *utils.ReadBuffer, datapointType KnxDatapointType) (ap
             }
 
             // Simple Field (value)
-            value, _valueErr := io.ReadString(112)
+            value, _valueErr := io.ReadString(-1)
             if _valueErr != nil {
                 return nil, errors.New("Error parsing 'value' field " + _valueErr.Error())
             }
@@ -2903,7 +2903,7 @@ func KnxDatapointParse(io *utils.ReadBuffer, datapointType KnxDatapointType) (ap
             }
 
             // Simple Field (value)
-            value, _valueErr := io.ReadString(112)
+            value, _valueErr := io.ReadString(-1)
             if _valueErr != nil {
                 return nil, errors.New("Error parsing 'value' field " + _valueErr.Error())
             }
@@ -5850,7 +5850,7 @@ func KnxDatapointParse(io *utils.ReadBuffer, datapointType KnxDatapointType) (ap
             }
 
             // Simple Field (value)
-            value, _valueErr := io.ReadString(16)
+            value, _valueErr := io.ReadString(-1)
             if _valueErr != nil {
                 return nil, errors.New("Error parsing 'value' field " + _valueErr.Error())
             }
@@ -7350,7 +7350,7 @@ func KnxDatapointSerialize(io *utils.WriteBuffer, value api.PlcValue, datapointT
             }
 
             // Simple Field (value)
-            if _err := io.WriteString(8, "ASCII", value.GetString()); _err != nil {
+            if _err := io.WriteString(-1, "ASCII", value.GetString()); _err != nil {
                 return errors.New("Error serializing 'value' field " + _err.Error())
             }
         case datapointType == KnxDatapointType_DPT_Char_8859_1: // STRING
@@ -7361,7 +7361,7 @@ func KnxDatapointSerialize(io *utils.WriteBuffer, value api.PlcValue, datapointT
             }
 
             // Simple Field (value)
-            if _err := io.WriteString(8, "ISO-8859-1", value.GetString()); _err != nil {
+            if _err := io.WriteString(-1, "ISO-8859-1", value.GetString()); _err != nil {
                 return errors.New("Error serializing 'value' field " + _err.Error())
             }
         case datapointType == KnxDatapointType_DPT_Scaling: // USINT
@@ -9219,7 +9219,7 @@ func KnxDatapointSerialize(io *utils.WriteBuffer, value api.PlcValue, datapointT
             }
 
             // Simple Field (value)
-            if _err := io.WriteString(112, "ASCII", value.GetString()); _err != nil {
+            if _err := io.WriteString(-1, "ASCII", value.GetString()); _err != nil {
                 return errors.New("Error serializing 'value' field " + _err.Error())
             }
         case datapointType == KnxDatapointType_DPT_String_8859_1: // STRING
@@ -9230,7 +9230,7 @@ func KnxDatapointSerialize(io *utils.WriteBuffer, value api.PlcValue, datapointT
             }
 
             // Simple Field (value)
-            if _err := io.WriteString(112, "ISO-8859-1", value.GetString()); _err != nil {
+            if _err := io.WriteString(-1, "ISO-8859-1", value.GetString()); _err != nil {
                 return errors.New("Error serializing 'value' field " + _err.Error())
             }
         case datapointType == KnxDatapointType_DPT_SceneNumber: // USINT
@@ -11479,7 +11479,7 @@ func KnxDatapointSerialize(io *utils.WriteBuffer, value api.PlcValue, datapointT
             }
 
             // Simple Field (value)
-            if _err := io.WriteString(16, "ASCII", value.GetString()); _err != nil {
+            if _err := io.WriteString(-1, "ASCII", value.GetString()); _err != nil {
                 return errors.New("Error serializing 'value' field " + _err.Error())
             }
         case datapointType == KnxDatapointType_DPT_Tariff_ActiveEnergy: // Struct
diff --git a/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/config/OpcuaConfiguration.java b/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/config/OpcuaConfiguration.java
index 4187173..0d5ea6b 100644
--- a/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/config/OpcuaConfiguration.java
+++ b/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/config/OpcuaConfiguration.java
@@ -50,6 +50,9 @@ public class OpcuaConfiguration implements Configuration, TcpTransportConfigurat
         Security.addProvider(new BouncyCastleProvider());
     }
 
+    private static final String nameSpaceSecurityPolicyNone = "http://opcfoundation.org/UA/SecurityPolicy#None";
+    private static final String nameSpaceSecurityPolicyUserName = "http://opcfoundation.org/UA/SecurityPolicy#Basic256Sha256";
+
     private static final Logger LOGGER = LoggerFactory.getLogger(OpcuaConfiguration.class);
 
     private String code;
@@ -175,7 +178,7 @@ public class OpcuaConfiguration implements Configuration, TcpTransportConfigurat
         this.endpoint = endpoint;
     }
 
-    public void openKeyStore() throws KeyStoreException, PlcConnectionException, CertificateException, NoSuchAlgorithmException, IOException, UnrecoverableKeyException {
+    public void openKeyStore() throws Exception {
         File securityTempDir = new File(certDirectory, "security");
         if (!securityTempDir.exists() && !securityTempDir.mkdirs()) {
             throw new PlcConnectionException("Unable to create directory please confirm folder permissions on "  + certDirectory);
diff --git a/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/context/CertificateKeyPair.java b/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/context/CertificateKeyPair.java
index a70aa3b..6b33a49 100644
--- a/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/context/CertificateKeyPair.java
+++ b/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/context/CertificateKeyPair.java
@@ -20,19 +20,25 @@
 package org.apache.plc4x.java.opcua.context;
 
 import java.security.KeyPair;
+import java.security.MessageDigest;
 import java.security.cert.X509Certificate;
 
 public class CertificateKeyPair {
 
     private final KeyPair keyPair;
     private final X509Certificate certificate;
+    private final byte[] thumbprint;
 
-    public CertificateKeyPair(KeyPair keyPair, X509Certificate certificate) {
+    public CertificateKeyPair(KeyPair keyPair, X509Certificate certificate) throws Exception{
         this.keyPair = keyPair;
         this.certificate = certificate;
+        MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
+        this.thumbprint = messageDigest.digest(this.certificate.getEncoded());
     }
 
     public KeyPair getKeyPair() { return keyPair; }
 
     public X509Certificate getCertificate() { return certificate; }
+
+    public byte[] getThumbPrint() { return thumbprint; }
 }
diff --git a/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/protocol/OpcuaProtocolLogic.java b/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/protocol/OpcuaProtocolLogic.java
index 1689fa8..6fa97e9 100644
--- a/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/protocol/OpcuaProtocolLogic.java
+++ b/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/protocol/OpcuaProtocolLogic.java
@@ -29,15 +29,16 @@ import org.apache.plc4x.java.api.messages.PlcWriteResponse;
 import org.apache.plc4x.java.api.types.PlcResponseCode;
 import org.apache.plc4x.java.api.value.PlcValue;
 import org.apache.plc4x.java.opcua.config.OpcuaConfiguration;
+import org.apache.plc4x.java.opcua.context.CertificateKeyPair;
 import org.apache.plc4x.java.opcua.readwrite.*;
-import org.apache.plc4x.java.opcua.readwrite.io.PascalStringIO;
-import org.apache.plc4x.java.opcua.readwrite.io.UserNameIdentityTokenIO;
+import org.apache.plc4x.java.opcua.readwrite.io.*;
 import org.apache.plc4x.java.opcua.readwrite.types.*;
 import org.apache.plc4x.java.spi.ConversationContext;
 import org.apache.plc4x.java.spi.Plc4xProtocolBase;
 import org.apache.plc4x.java.spi.configuration.HasConfiguration;
 import org.apache.plc4x.java.spi.context.DriverContext;
 import org.apache.plc4x.java.spi.generation.ParseException;
+import org.apache.plc4x.java.spi.generation.ReadBuffer;
 import org.apache.plc4x.java.spi.generation.WriteBuffer;
 import org.apache.plc4x.java.spi.messages.DefaultPlcReadRequest;
 import org.apache.plc4x.java.spi.messages.DefaultPlcReadResponse;
@@ -55,6 +56,7 @@ import java.io.ByteArrayInputStream;
 import java.math.BigInteger;
 import java.nio.ByteBuffer;
 import java.nio.ByteOrder;
+import java.security.cert.CertificateEncodingException;
 import java.security.cert.CertificateFactory;
 import java.security.cert.X509Certificate;
 import java.time.Duration;
@@ -97,13 +99,11 @@ public class OpcuaProtocolLogic extends Plc4xProtocolBase<OpcuaAPU> implements H
     private static final long epochOffset = 116444736000000000L;         //Offset between OPC UA epoch time and linux epoch time.
 
     private static final String CHUNK = "F";
-    private static final String nameSpaceSecurityPolicyNone = "http://opcfoundation.org/UA/SecurityPolicy#None";
-    private static final String nameSpaceSecurityPolicyUserName = "http://opcfoundation.org/UA/SecurityPolicy#Basic256Sha256";
+
     private static final String applicationUri = "urn:apache:plc4x:client";
     private static final String productUri = "urn:apache:plc4x:client";
     private static final String applicationText = "OPCUA client for the Apache PLC4X:PLC4J project";
 
-
     private final String sessionName = "UaSession:" + applicationText + ":" + RandomStringUtils.random(20, true, true);
     private final byte[] clientNonce = RandomUtils.nextBytes(40);
     private RequestTransactionManager tm;
@@ -116,6 +116,11 @@ public class OpcuaProtocolLogic extends Plc4xProtocolBase<OpcuaAPU> implements H
     private String certFile;
     private String securityPolicy;
     private String keyStoreFile;
+    private CertificateKeyPair ckp;
+    private PascalByteString publicCertificate;
+    private PascalByteString thumbprint;
+    private boolean isEncrypted;
+    private boolean checkedEndpoints = false;
     private AtomicInteger transactionIdentifierGenerator = new AtomicInteger(1);
     private AtomicInteger requestHandleGenerator = new AtomicInteger(1);
     private AtomicInteger tokenId = new AtomicInteger(1);
@@ -133,7 +138,24 @@ public class OpcuaProtocolLogic extends Plc4xProtocolBase<OpcuaAPU> implements H
         this.username = configuration.getUsername();
         this.password = configuration.getPassword();
         this.certFile = configuration.getCertDirectory();
-        this.securityPolicy = configuration.getSecurityPolicy();
+        this.securityPolicy = "http://opcfoundation.org/UA/SecurityPolicy#" + configuration.getSecurityPolicy();
+        LOGGER.info("---------------------------------------");
+        LOGGER.info(configuration.getSecurityPolicy());
+        this.ckp = configuration.getCertificateKeyPair();
+        if (configuration.getSecurityPolicy().equals("Basic256Sha256")) {
+            try {
+                this.publicCertificate = new PascalByteString(this.ckp.getCertificate().getEncoded().length, this.ckp.getCertificate().getEncoded());
+                this.isEncrypted = true;
+            } catch (CertificateEncodingException e) {
+                LOGGER.error("Failed to encode the certificate");
+            }
+            //this.thumbprint = new PascalByteString(this.ckp.getThumbPrint().length, this.ckp.getThumbPrint());
+            this.thumbprint =NULL_BYTE_STRING;
+        } else {
+            this.publicCertificate = NULL_BYTE_STRING;
+            this.thumbprint = NULL_BYTE_STRING;
+            this.isEncrypted = false;
+        }
         this.keyStoreFile = configuration.getKeyStoreFile();
 
         this.tm = new RequestTransactionManager(1);
@@ -169,21 +191,28 @@ public class OpcuaProtocolLogic extends Plc4xProtocolBase<OpcuaAPU> implements H
             requestHeader,
             true);
 
-        OpcuaMessageRequest messageRequest = new OpcuaMessageRequest(CHUNK,
-            channelId.get(),
-            tokenId.get(),
-            transactionId,
-            transactionId,
-            closeSessionRequest);
-
-        context.sendRequest(new OpcuaAPU(messageRequest))
-            .expectResponse(OpcuaAPU.class, REQUEST_TIMEOUT)
-            .check(p -> p.getMessage() instanceof OpcuaMessageResponse)
-            .unwrap(p -> (OpcuaMessageResponse) p.getMessage())
-            .handle(opcuaMessageResponse -> {
-                    LOGGER.info("Got Close Session Response Connection Response" + opcuaMessageResponse.toString());
-                    onDisconnectCloseSecureChannel(context);
-                });
+        try {
+            WriteBuffer buffer = new WriteBuffer(closeSessionRequest.getLengthInBytes(), true);
+            OpcuaMessageIO.staticSerialize(buffer, closeSessionRequest);
+
+            OpcuaMessageRequest messageRequest = new OpcuaMessageRequest(CHUNK,
+                channelId.get(),
+                tokenId.get(),
+                transactionId,
+                transactionId,
+                buffer.getData());
+
+            context.sendRequest(new OpcuaAPU(messageRequest))
+                .expectResponse(OpcuaAPU.class, REQUEST_TIMEOUT)
+                .check(p -> p.getMessage() instanceof OpcuaMessageResponse)
+                .unwrap(p -> (OpcuaMessageResponse) p.getMessage())
+                .handle(opcuaMessageResponse -> {
+                        LOGGER.info("Got Close Session Response Connection Response" + opcuaMessageResponse.toString());
+                        onDisconnectCloseSecureChannel(context);
+                    });
+        } catch (ParseException e) {
+            LOGGER.error("Failed to parse the Message Request");
+        }
     }
 
     private void onDisconnectCloseSecureChannel(ConversationContext<OpcuaAPU> context) {
@@ -257,7 +286,182 @@ public class OpcuaProtocolLogic extends Plc4xProtocolBase<OpcuaAPU> implements H
             .unwrap(p -> (OpcuaAcknowledgeResponse) p.getMessage())
             .handle(opcuaAcknowledgeResponse -> {
                 LOGGER.debug("Got Hello Response Connection Response");
-                onConnectOpenSecureChannel(context, opcuaAcknowledgeResponse);
+                if (this.isEncrypted & !this.checkedEndpoints) {
+                    onConnectGetEndpointsOpenSecureChannel(context, opcuaAcknowledgeResponse);
+                } else {
+                    onConnectOpenSecureChannel(context, opcuaAcknowledgeResponse);
+                }
+            });
+    }
+
+    public void onConnectGetEndpointsOpenSecureChannel(ConversationContext<OpcuaAPU> context, OpcuaAcknowledgeResponse opcuaAcknowledgeResponse) {
+        int transactionId = getTransactionIdentifier(securedConnection.get());
+
+        ExpandedNodeId expandedNodeId = new ExpandedNodeIdFourByte(false,           //Namespace Uri Specified
+            false,            //Server Index Specified
+            NULL_STRING,                      //Namespace Uri
+            1L,                     //Server Index
+            new FourByteNodeId((short) 0, 466));    //Identifier for OpenSecureChannel
+
+        RequestHeader requestHeader = new RequestHeader(authenticationToken,
+            getCurrentDateTime(),
+            0L,                                         //RequestHandle
+            0L,
+            NULL_STRING,
+            REQUEST_TIMEOUT_LONG,
+            NULL_EXTENSION_OBJECT);
+
+        OpenSecureChannelRequest openSecureChannelRequest = new OpenSecureChannelRequest((byte) 1,
+            (byte) 0,
+            requestHeader,
+            VERSION,
+            SecurityTokenRequestType.securityTokenRequestTypeIssue,
+            MessageSecurityMode.messageSecurityModeNone,
+            NULL_BYTE_STRING,
+            DEFAULT_CONNECTION_LIFETIME);
+
+        OpcuaOpenRequest openRequest = new OpcuaOpenRequest(CHUNK,
+            0,
+            new PascalString("http://opcfoundation.org/UA/SecurityPolicy#None".length(), "http://opcfoundation.org/UA/SecurityPolicy#None"),
+            NULL_BYTE_STRING,
+            NULL_BYTE_STRING,
+            transactionId,
+            transactionId,
+            openSecureChannelRequest);
+
+        context.sendRequest(new OpcuaAPU(openRequest))
+            .expectResponse(OpcuaAPU.class, REQUEST_TIMEOUT)
+            .check(p -> p.getMessage() instanceof OpcuaOpenResponse)
+            .unwrap(p -> (OpcuaOpenResponse) p.getMessage())
+            .handle(opcuaOpenResponse -> {
+                if (opcuaOpenResponse.getMessage() instanceof ServiceFault) {
+                    ServiceFault fault = (ServiceFault) opcuaOpenResponse.getMessage();
+                    LOGGER.error("Failed to connect to opc ua server for the following reason:- {}, {}", fault.getResponseHeader().getServiceResult().getStatusCode(), OpcuaStatusCodes.enumForValue(fault.getResponseHeader().getServiceResult().getStatusCode()));
+                } else {
+                    LOGGER.debug("Got Secure Response Connection Response");
+                    try {
+                        onConnectGetEndpointsRequest(context, opcuaOpenResponse);
+                    } catch (PlcConnectionException e) {
+                        LOGGER.error("Error occurred while connecting to OPC UA server");
+                    }
+                }
+            });
+    }
+
+    public void onConnectGetEndpointsRequest(ConversationContext<OpcuaAPU> context, OpcuaOpenResponse opcuaOpenResponse) throws PlcConnectionException {
+        certificateThumbprint = opcuaOpenResponse.getReceiverCertificateThumbprint();
+        OpenSecureChannelResponse openSecureChannelResponse = (OpenSecureChannelResponse) opcuaOpenResponse.getMessage();
+        tokenId.set((int) openSecureChannelResponse.getSecurityToken().getTokenId());
+        channelId.set((int) openSecureChannelResponse.getSecurityToken().getChannelId());
+
+        int transactionId = getTransactionIdentifier(securedConnection.get());
+
+        Integer nextSequenceNumber = opcuaOpenResponse.getSequenceNumber() + 1;
+        Integer nextRequestId = opcuaOpenResponse.getRequestId() + 1;
+
+        if (!(transactionId == nextSequenceNumber)) {
+            LOGGER.error("Sequence number isn't as expected, we might have missed a packet. - " +  transactionId + " != " + nextSequenceNumber);
+            throw new PlcConnectionException("Sequence number isn't as expected, we might have missed a packet. - " +  transactionId + " != " + nextSequenceNumber);
+        }
+
+        RequestHeader requestHeader = new RequestHeader(authenticationToken,
+            getCurrentDateTime(),
+            0L,
+            0L,
+            NULL_STRING,
+            REQUEST_TIMEOUT_LONG,
+            NULL_EXTENSION_OBJECT);
+
+        GetEndpointsRequest endpointsRequest = new GetEndpointsRequest((byte) 1,
+            (byte) 0,
+            requestHeader,
+            new PascalString(this.endpoint.length(), this.endpoint),
+            0,
+            null,
+            0,
+            null);
+
+        try {
+            WriteBuffer buffer = new WriteBuffer(endpointsRequest.getLengthInBytes(), true);
+            OpcuaMessageIO.staticSerialize(buffer, endpointsRequest);
+
+            OpcuaMessageRequest messageRequest = new OpcuaMessageRequest(CHUNK,
+                channelId.get(),
+                tokenId.get(),
+                nextSequenceNumber,
+                nextRequestId,
+                buffer.getData());
+
+            context.sendRequest(new OpcuaAPU(messageRequest))
+                .expectResponse(OpcuaAPU.class, REQUEST_TIMEOUT)
+                .check(p -> p.getMessage() instanceof OpcuaMessageResponse)
+                .unwrap(p -> (OpcuaMessageResponse) p.getMessage())
+                .handle(opcuaMessageResponse -> {
+                    try {
+                        OpcuaMessage message = OpcuaMessageIO.staticParse(new ReadBuffer(opcuaMessageResponse.getMessage(), true));
+                        if (message instanceof ServiceFault) {
+                            ServiceFault fault = (ServiceFault) message;
+                            LOGGER.error("Failed to connect to opc ua server for the following reason:- {}, {}", fault.getResponseHeader().getServiceResult().getStatusCode(), OpcuaStatusCodes.enumForValue(fault.getResponseHeader().getServiceResult().getStatusCode()));
+                        } else {
+                            LOGGER.debug("Got Create Session Response Connection Response");
+                            onConnectGetEndpointsCloseSecureChannel(context, (GetEndpointsResponse) message);
+                        }
+                    } catch (ParseException e) {
+                        e.printStackTrace();
+                    }
+
+                });
+        } catch (ParseException e) {
+            LOGGER.error("Unable to to Parse Create Session Request");
+        }
+    }
+
+    private void onConnectGetEndpointsCloseSecureChannel(ConversationContext<OpcuaAPU> context, GetEndpointsResponse message) {
+
+        int transactionId = getTransactionIdentifier(securedConnection.get());
+        EndpointDescription[] endpoints = message.getEndpoints();
+        for (EndpointDescription endpoint : endpoints) {
+            if (endpoint.getEndpointUrl().getStringValue().equals(this.endpoint) && endpoint.getSecurityPolicyUri().getStringValue().equals(this.securityPolicy)) {
+                LOGGER.info("Found OPC UA endpoint {}", this.endpoint);
+                this.senderCertificate = endpoint.getServerCertificate().getStringValue();
+            }
+        }
+
+        ExpandedNodeId expandedNodeId = new ExpandedNodeIdFourByte(false,           //Namespace Uri Specified
+            false,            //Server Index Specified
+            NULL_STRING,                      //Namespace Uri
+            1L,                     //Server Index
+            new FourByteNodeId((short) 0, 452));    //Identifier for CloseSecureChannel
+
+        RequestHeader requestHeader = new RequestHeader(authenticationToken,
+            getCurrentDateTime(),
+            0L,                                         //RequestHandle
+            0L,
+            NULL_STRING,
+            REQUEST_TIMEOUT_LONG,
+            NULL_EXTENSION_OBJECT);
+
+        CloseSecureChannelRequest closeSecureChannelRequest = new CloseSecureChannelRequest((byte) 1,
+            (byte) 0,
+            requestHeader);
+
+        OpcuaCloseRequest closeRequest = new OpcuaCloseRequest(CHUNK,
+            channelId.get(),
+            tokenId.get(),
+            transactionId,
+            transactionId,
+            closeSecureChannelRequest);
+
+        context.sendRequest(new OpcuaAPU(closeRequest))
+            .expectResponse(OpcuaAPU.class, REQUEST_TIMEOUT)
+            .check(p -> p.getMessage() instanceof OpcuaMessageResponse)
+            .unwrap(p -> (OpcuaMessageResponse) p.getMessage())
+            .handle(opcuaMessageResponse -> {
+                LOGGER.info("Got Close Secure Channel Response" + opcuaMessageResponse.toString());
+                this.checkedEndpoints = true;
+                channelId.set(0);
+                tokenId.set(0);
+                onConnect(context);
             });
     }
 
@@ -290,9 +494,9 @@ public class OpcuaProtocolLogic extends Plc4xProtocolBase<OpcuaAPU> implements H
 
         OpcuaOpenRequest openRequest = new OpcuaOpenRequest(CHUNK,
             0,
-            new PascalString(nameSpaceSecurityPolicyNone.length(), nameSpaceSecurityPolicyNone),
-            NULL_STRING,
-            NULL_STRING,
+            new PascalString(this.securityPolicy.length(), this.securityPolicy),
+            this.publicCertificate,
+            this.thumbprint,
             transactionId,
             transactionId,
             openSecureChannelRequest);
@@ -352,7 +556,7 @@ public class OpcuaProtocolLogic extends Plc4xProtocolBase<OpcuaAPU> implements H
         PascalString gatewayServerUri = NULL_STRING;
         PascalString discoveryProfileUri = NULL_STRING;
         int noOfDiscoveryUrls = -1;
-        PascalString discoveryUrls = null;
+        PascalString[] discoveryUrls = new PascalString[0];
 
         ApplicationDescription clientDescription = new ApplicationDescription(new PascalString(applicationUri.length(), applicationUri),
             new PascalString(productUri.length(), productUri),
@@ -375,35 +579,48 @@ public class OpcuaProtocolLogic extends Plc4xProtocolBase<OpcuaAPU> implements H
             120000L,
             0L);
 
-        OpcuaMessageRequest messageRequest = new OpcuaMessageRequest(CHUNK,
-            channelId.get(),
-            tokenId.get(),
-            nextSequenceNumber,
-            nextRequestId,
-            createSessionRequest);
-
-        context.sendRequest(new OpcuaAPU(messageRequest))
-            .expectResponse(OpcuaAPU.class, REQUEST_TIMEOUT)
-            .check(p -> p.getMessage() instanceof OpcuaMessageResponse)
-            .unwrap(p -> (OpcuaMessageResponse) p.getMessage())
-            .handle(opcuaMessageResponse -> {
-                if (opcuaMessageResponse.getMessage() instanceof ServiceFault) {
-                    ServiceFault fault = (ServiceFault) opcuaMessageResponse.getMessage();
-                    LOGGER.error("Failed to connect to opc ua server for the following reason:- {}, {}", fault.getResponseHeader().getServiceResult().getStatusCode(), OpcuaStatusCodes.enumForValue(fault.getResponseHeader().getServiceResult().getStatusCode()));
-                } else {
-                    LOGGER.debug("Got Create Session Response Connection Response");
+        try {
+            WriteBuffer buffer = new WriteBuffer(createSessionRequest.getLengthInBytes(), true);
+            OpcuaMessageIO.staticSerialize(buffer, createSessionRequest);
+
+            OpcuaMessageRequest messageRequest = new OpcuaMessageRequest(CHUNK,
+                channelId.get(),
+                tokenId.get(),
+                nextSequenceNumber,
+                nextRequestId,
+                buffer.getData());
+
+            context.sendRequest(new OpcuaAPU(messageRequest))
+                .expectResponse(OpcuaAPU.class, REQUEST_TIMEOUT)
+                .check(p -> p.getMessage() instanceof OpcuaMessageResponse)
+                .unwrap(p -> (OpcuaMessageResponse) p.getMessage())
+                .handle(opcuaMessageResponse -> {
                     try {
-                        onConnectActivateSessionRequest(context, opcuaMessageResponse);
-                    } catch (PlcConnectionException e) {
-                        LOGGER.error("Error occurred while connecting to OPC UA server");
+                        OpcuaMessage message = OpcuaMessageIO.staticParse(new ReadBuffer(opcuaMessageResponse.getMessage(), true));
+                        if (message instanceof ServiceFault) {
+                            ServiceFault fault = (ServiceFault) message;
+                            LOGGER.error("Failed to connect to opc ua server for the following reason:- {}, {}", fault.getResponseHeader().getServiceResult().getStatusCode(), OpcuaStatusCodes.enumForValue(fault.getResponseHeader().getServiceResult().getStatusCode()));
+                        } else {
+                            LOGGER.debug("Got Create Session Response Connection Response");
+                            try {
+                                onConnectActivateSessionRequest(context, opcuaMessageResponse, (CreateSessionResponse) message);
+                            } catch (PlcConnectionException e) {
+                                LOGGER.error("Error occurred while connecting to OPC UA server");
+                            }
+                        }
+                    } catch (ParseException e) {
+                        e.printStackTrace();
                     }
-                }
-            });
+
+                });
+        } catch (ParseException e) {
+            LOGGER.error("Unable to to Parse Create Session Request");
+        }
     }
 
-    private void onConnectActivateSessionRequest(ConversationContext<OpcuaAPU> context, OpcuaMessageResponse opcuaMessageResponse) throws PlcConnectionException {
+    private void onConnectActivateSessionRequest(ConversationContext<OpcuaAPU> context, OpcuaMessageResponse opcuaMessageResponse, CreateSessionResponse sessionResponse) throws PlcConnectionException {
 
-        CreateSessionResponse createSessionResponse = (CreateSessionResponse) opcuaMessageResponse.getMessage();
+        CreateSessionResponse createSessionResponse = sessionResponse;
         senderCertificate = createSessionResponse.getServerCertificate().getStringValue();
         senderNonce = createSessionResponse.getServerNonce().getStringValue();
 
@@ -474,34 +691,47 @@ public class OpcuaProtocolLogic extends Plc4xProtocolBase<OpcuaAPU> implements H
             userIdentityToken,
             clientSignature);
 
-        OpcuaMessageRequest activateMessageRequest = new OpcuaMessageRequest(CHUNK,
-            channelId.get(),
-            tokenId.get(),
-            nextSequenceNumber,
-            nextRequestId,
-            activateSessionRequest);
-
-        context.sendRequest(new OpcuaAPU(activateMessageRequest))
-            .expectResponse(OpcuaAPU.class, REQUEST_TIMEOUT)
-            .check(p -> p.getMessage() instanceof OpcuaMessageResponse)
-            .unwrap(p -> (OpcuaMessageResponse) p.getMessage())
-            .handle(opcuaActivateResponse -> {
-                LOGGER.debug("Got Activate Session Response Connection Response");
-                if (opcuaActivateResponse.getMessage() instanceof ServiceFault) {
-                    ServiceFault fault = (ServiceFault) opcuaActivateResponse.getMessage();
-                    LOGGER.error("Failed to connect to opc ua server for the following reason:- {}, {}", fault.getResponseHeader().getServiceResult().getStatusCode(), OpcuaStatusCodes.enumForValue(fault.getResponseHeader().getServiceResult().getStatusCode()));
-                } else {
-                    ActivateSessionResponse activateMessageResponse = (ActivateSessionResponse) opcuaActivateResponse.getMessage();
-
-                    long returnedRequestHandle = activateMessageResponse.getResponseHeader().getRequestHandle();
-                    if (!(requestHandle == returnedRequestHandle)) {
-                        LOGGER.error("Request handle isn't as expected, we might have missed a packet. {} != {}" ,requestHandle,  returnedRequestHandle);
+        try {
+            WriteBuffer buffer = new WriteBuffer(activateSessionRequest.getLengthInBytes(), true);
+            OpcuaMessageIO.staticSerialize(buffer, activateSessionRequest);
+
+            OpcuaMessageRequest activateMessageRequest = new OpcuaMessageRequest(CHUNK,
+                channelId.get(),
+                tokenId.get(),
+                nextSequenceNumber,
+                nextRequestId,
+                buffer.getData());
+
+            context.sendRequest(new OpcuaAPU(activateMessageRequest))
+                .expectResponse(OpcuaAPU.class, REQUEST_TIMEOUT)
+                .check(p -> p.getMessage() instanceof OpcuaMessageResponse)
+                .unwrap(p -> (OpcuaMessageResponse) p.getMessage())
+                .handle(opcuaActivateResponse -> {
+                    LOGGER.debug("Got Activate Session Response Connection Response");
+                    try {
+                        OpcuaMessage message = OpcuaMessageIO.staticParse(new ReadBuffer(opcuaActivateResponse.getMessage(), true));
+                        if (message instanceof ServiceFault) {
+                            ServiceFault fault = (ServiceFault) message;
+                            LOGGER.error("Failed to connect to opc ua server for the following reason:- {}, {}", fault.getResponseHeader().getServiceResult().getStatusCode(), OpcuaStatusCodes.enumForValue(fault.getResponseHeader().getServiceResult().getStatusCode()));
+                        } else {
+                            ActivateSessionResponse activateMessageResponse = (ActivateSessionResponse) message;
+
+                            long returnedRequestHandle = activateMessageResponse.getResponseHeader().getRequestHandle();
+                            if (!(requestHandle == returnedRequestHandle)) {
+                                LOGGER.error("Request handle isn't as expected, we might have missed a packet. {} != {}", requestHandle, returnedRequestHandle);
+                            }
+
+                            // Send an event that connection setup is complete.
+                            context.fireConnected();
+                        }
+                    } catch (ParseException e) {
+                        e.printStackTrace();
                     }
 
-                    // Send an event that connection setup is complete.
-                    context.fireConnected();
-                }
-            });
+                });
+        } catch (ParseException e) {
+            LOGGER.info("Unable to serialise the ActivateSessionRequest");
+        }
     }
 
     @Override
@@ -553,31 +783,42 @@ public class OpcuaProtocolLogic extends Plc4xProtocolBase<OpcuaAPU> implements H
 
         int transactionId = getTransactionIdentifier(securedConnection.get());
 
-        OpcuaMessageRequest readMessageRequest = new OpcuaMessageRequest(CHUNK,
-            channelId.get(),
-            tokenId.get(),
-            transactionId,
-            transactionId,
-            opcuaReadRequest);
-
-        RequestTransactionManager.RequestTransaction transaction = tm.startRequest();
-        transaction.submit(() -> context.sendRequest(new OpcuaAPU(readMessageRequest))
-            .expectResponse(OpcuaAPU.class, REQUEST_TIMEOUT)
-            .onTimeout(future::completeExceptionally)
-            .onError((p, e) -> future.completeExceptionally(e))
-            .check(p -> p.getMessage() instanceof OpcuaMessageResponse)
-            .unwrap(p -> (OpcuaMessageResponse) p.getMessage())
-            .handle(opcuaResponse -> {
-                // Prepare the response.
-                PlcReadResponse response = new DefaultPlcReadResponse(request,
-                    readResponse(request.getFieldNames(), (ReadResponse) opcuaResponse.getMessage()));
-
-                // Pass the response back to the application.
-                future.complete(response);
-
-                // Finish the request-transaction.
-                transaction.endRequest();
-            }));
+        try {
+            WriteBuffer buffer = new WriteBuffer(opcuaReadRequest.getLengthInBytes(), true);
+            OpcuaMessageIO.staticSerialize(buffer, opcuaReadRequest);
+
+            OpcuaMessageRequest readMessageRequest = new OpcuaMessageRequest(CHUNK,
+                channelId.get(),
+                tokenId.get(),
+                transactionId,
+                transactionId,
+                buffer.getData());
+
+            RequestTransactionManager.RequestTransaction transaction = tm.startRequest();
+            transaction.submit(() -> context.sendRequest(new OpcuaAPU(readMessageRequest))
+                .expectResponse(OpcuaAPU.class, REQUEST_TIMEOUT)
+                .onTimeout(future::completeExceptionally)
+                .onError((p, e) -> future.completeExceptionally(e))
+                .check(p -> p.getMessage() instanceof OpcuaMessageResponse)
+                .unwrap(p -> (OpcuaMessageResponse) p.getMessage())
+                .handle(opcuaResponse -> {
+                    // Prepare the response.
+                    PlcReadResponse response = null;
+                    try {
+                        response = new DefaultPlcReadResponse(request, readResponse(request.getFieldNames(), (ReadResponse) OpcuaMessageIO.staticParse(new ReadBuffer(opcuaResponse.getMessage(), true))));
+                    } catch (ParseException e) {
+                        e.printStackTrace();
+                    };
+
+                    // Pass the response back to the application.
+                    future.complete(response);
+
+                    // Finish the request-transaction.
+                    transaction.endRequest();
+                }));
+        } catch (ParseException e) {
+            LOGGER.error("Unable to serialise the ReadRequest");
+        }
 
         return future;
     }
@@ -1060,30 +1301,42 @@ public class OpcuaProtocolLogic extends Plc4xProtocolBase<OpcuaAPU> implements H
 
         int transactionId = getTransactionIdentifier(securedConnection.get());
 
-        OpcuaMessageRequest writeMessageRequest = new OpcuaMessageRequest(CHUNK,
-            channelId.get(),
-            tokenId.get(),
-            transactionId,
-            transactionId,
-            opcuaWriteRequest);
-
-        RequestTransactionManager.RequestTransaction transaction = tm.startRequest();
-        transaction.submit(() -> context.sendRequest(new OpcuaAPU(writeMessageRequest))
-            .expectResponse(OpcuaAPU.class, REQUEST_TIMEOUT)
-            .onTimeout(future::completeExceptionally)
-            .onError((p, e) -> future.completeExceptionally(e))
-            .check(p -> p.getMessage() instanceof OpcuaMessageResponse)
-            .unwrap(p -> (OpcuaMessageResponse) p.getMessage())
-            .handle(opcuaResponse -> {
-                WriteResponse responseMessage = (WriteResponse) opcuaResponse.getMessage();
-                PlcWriteResponse response = writeResponse(request, responseMessage);
+        try {
+            WriteBuffer buffer = new WriteBuffer(opcuaWriteRequest.getLengthInBytes(), true);
+            OpcuaMessageIO.staticSerialize(buffer, opcuaWriteRequest);
+
+            OpcuaMessageRequest writeMessageRequest = new OpcuaMessageRequest(CHUNK,
+                channelId.get(),
+                tokenId.get(),
+                transactionId,
+                transactionId,
+                buffer.getData());
+
+            RequestTransactionManager.RequestTransaction transaction = tm.startRequest();
+            transaction.submit(() -> context.sendRequest(new OpcuaAPU(writeMessageRequest))
+                .expectResponse(OpcuaAPU.class, REQUEST_TIMEOUT)
+                .onTimeout(future::completeExceptionally)
+                .onError((p, e) -> future.completeExceptionally(e))
+                .check(p -> p.getMessage() instanceof OpcuaMessageResponse)
+                .unwrap(p -> (OpcuaMessageResponse) p.getMessage())
+                .handle(opcuaResponse -> {
+                    WriteResponse responseMessage = null;
+                    try {
+                        responseMessage = (WriteResponse) OpcuaMessageIO.staticParse(new ReadBuffer(opcuaResponse.getMessage(), true));
+                    } catch (ParseException e) {
+                        e.printStackTrace();
+                    }
+                    PlcWriteResponse response = writeResponse(request, responseMessage);
 
-                // Pass the response back to the application.
-                future.complete(response);
+                    // Pass the response back to the application.
+                    future.complete(response);
 
-                // Finish the request-transaction.
-                transaction.endRequest();
-            }));
+                    // Finish the request-transaction.
+                    transaction.endRequest();
+                }));
+        } catch (ParseException e) {
+            LOGGER.info("Unable to serialize write request");
+        }
 
         return future;
     }
diff --git a/protocols/knxnetip/src/main/resources/protocols/knxnetip/knxnetip.mspec b/protocols/knxnetip/src/main/resources/protocols/knxnetip/knxnetip.mspec
index 916e086..349c625 100644
--- a/protocols/knxnetip/src/main/resources/protocols/knxnetip/knxnetip.mspec
+++ b/protocols/knxnetip/src/main/resources/protocols/knxnetip/knxnetip.mspec
@@ -649,7 +649,7 @@
     ['0x20' MEDIUM_KNX_IP]
 ]
 
-[enum uint 8 'SupportedPhysicalMedia' [string 'description',                                                    bit 'knxSupport']
+[enum uint 8 'SupportedPhysicalMedia' [string '-1' 'description',                                                    bit 'knxSupport']
     ['0x00' OTHER                     ['used_for_undefined_physical_medium',                                    'true']]
     ['0x01' OIL_METER                 ['measures_volume_of_oil',                                                'true']]
     ['0x02' ELECTRICITY_METER         ['measures_electric_energy',                                              'true']]
diff --git a/protocols/knxnetip/src/main/xslt/knx-types.xsl b/protocols/knxnetip/src/main/xslt/knx-types.xsl
index 7a63db5..a00ed10 100644
--- a/protocols/knxnetip/src/main/xslt/knx-types.xsl
+++ b/protocols/knxnetip/src/main/xslt/knx-types.xsl
@@ -47,33 +47,33 @@
 // specific language governing permissions and limitations
 // under the License.
 //
-[enum uint 16 'KnxDatapointMainType' [uint 16 'number', uint 8 'sizeInBits', string 'name']
+[enum uint 16 'KnxDatapointMainType' [uint 16 'number', uint 8 'sizeInBits', string '-1' 'name']
     ['0' DPT_UNKNOWN ['0', '0', '"Unknown Datapoint Type"']]
     <xsl:apply-templates select="knx:KNX/knx:MasterData/knx:DatapointTypes/knx:DatapointType"/>
 ]
 
-[enum uint 32 'KnxDatapointType' [uint 16 'number', KnxDatapointMainType 'datapointMainType', string 'name']
+[enum uint 32 'KnxDatapointType' [uint 16 'number', KnxDatapointMainType 'datapointMainType', string '-1' 'name']
     ['0' DPT_UNKNOWN ['0', 'KnxDatapointMainType.DPT_UNKNOWN', '"Unknown Datapoint Subtype"']]
     <xsl:apply-templates select="knx:KNX/knx:MasterData/knx:DatapointTypes/knx:DatapointType/knx:DatapointSubtypes/knx:DatapointSubtype"/>
 ]
 
-[enum uint 16 'KnxInterfaceObjectType' [string 'code', string 'name']
+[enum uint 16 'KnxInterfaceObjectType' [string '-1' 'code', string '-1' 'name']
     ['0' OT_UNKNOWN ['U', '"Unknown Interface Object Type"']]
     ['1' OT_GENERAL ['G', '"General Interface Object Type"']]
     <xsl:apply-templates select="knx:KNX/knx:MasterData/knx:InterfaceObjectTypes/knx:InterfaceObjectType"/>
 ]
 
-[enum uint 32 'KnxInterfaceObjectProperty' [uint 8 'propertyId', KnxInterfaceObjectType 'objectType', KnxPropertyDataType 'propertyDataType', string 'name']
+[enum uint 32 'KnxInterfaceObjectProperty' [uint 8 'propertyId', KnxInterfaceObjectType 'objectType', KnxPropertyDataType 'propertyDataType', string '-1' 'name']
     ['0' PID_UNKNOWN ['0', 'KnxInterfaceObjectType.OT_UNKNOWN', 'KnxPropertyDataType.PDT_UNKNOWN', '"Unknown Interface Object Property"']]
     <xsl:apply-templates select="knx:KNX/knx:MasterData/knx:InterfaceObjectProperties/knx:InterfaceObjectProperty"/>
 ]
 
-[enum uint 8 'KnxPropertyDataType' [uint 8 'number', uint 8 'sizeInBytes', string 'name']
+[enum uint 8 'KnxPropertyDataType' [uint 8 'number', uint 8 'sizeInBytes', string '-1' 'name']
     ['0' PDT_UNKNOWN ['0', '0', '"Unknown Property Data Type"']]
     <xsl:apply-templates select="knx:KNX/knx:MasterData/knx:PropertyDataTypes/knx:PropertyDataType"/>
 ]
 
-[enum uint 16 'KnxManufacturer' [uint 16 'number', string 'name']
+[enum uint 16 'KnxManufacturer' [uint 16 'number', string '-1' 'name']
     ['0' M_UNKNOWN ['0', '"Unknown Manufacturer"']]
     <xsl:apply-templates select="knx:KNX/knx:MasterData/knx:Manufacturers/knx:Manufacturer"/>
 ]
@@ -321,7 +321,7 @@
                     </xsl:choose>
                 </xsl:variable>
             [reserved uint 8   '0x0']
-            [simple   string <xsl:value-of select="$datapointSubtype/knx:Format/knx:String/@Width"/> '<xsl:value-of select="$encoding"/>' 'value']
+            [simple   string '<xsl:value-of select="$datapointSubtype/knx:Format/knx:String/@Width"/>' '<xsl:value-of select="$encoding"/>' 'value']
             </xsl:when>
             <xsl:when test="$datapointSubtype/knx:Format/knx:UnsignedInteger">
                 <xsl:choose>
@@ -400,7 +400,7 @@
                         <xsl:when test="$field/@Encoding = 'iso-8859-1'">ISO-8859-1</xsl:when>
                     </xsl:choose>
                 </xsl:variable>
-                string <xsl:value-of select="$field/@Width"/> '<xsl:value-of select="$encoding"/>'</xsl:when>
+                string '<xsl:value-of select="$field/@Width"/>' '<xsl:value-of select="$encoding"/>'</xsl:when>
             <xsl:when test="name($field) = 'UnsignedInteger'">uint <xsl:value-of select="$field/@Width"/></xsl:when>
             <xsl:when test="name($field) = 'SignedInteger'">int <xsl:value-of select="$field/@Width"/></xsl:when>
             <xsl:when test="name($field) = 'Float'">
diff --git a/protocols/opcua/src/main/resources/protocols/opcua/opcua.mspec b/protocols/opcua/src/main/resources/protocols/opcua/opcua.mspec
index ffd7ca2..8dd59a9 100644
--- a/protocols/opcua/src/main/resources/protocols/opcua/opcua.mspec
+++ b/protocols/opcua/src/main/resources/protocols/opcua/opcua.mspec
@@ -59,8 +59,8 @@
             [implicit        int 32             'messageSize' 'lengthInBytes']
             [simple          int 32             'secureChannelId']
             [simple          PascalString       'endpoint']
-            [simple          PascalString       'senderCertificate']
-            [simple          PascalString       'receiverCertificateThumbprint']
+            [simple          PascalByteString   'senderCertificate']
+            [simple          PascalByteString   'receiverCertificateThumbprint']
             [simple          int 32             'sequenceNumber']
             [simple          int 32             'requestId']
             [simple          OpcuaMessage       'message']
@@ -97,7 +97,7 @@
            [simple          int 32             'secureTokenId']
            [simple          int 32             'sequenceNumber']
            [simple          int 32             'requestId']
-           [simple          OpcuaMessage       'message']
+           [array           int 8              'message' count 'messageSize - 24']
        ]
        ['MSG','true'     OpcuaMessageResponse
            [simple          string '8'         'chunk']
@@ -106,7 +106,7 @@
            [simple          int 32             'secureTokenId']
            [simple          int 32             'sequenceNumber']
            [simple          int 32             'requestId']
-           [simple          OpcuaMessage       'message']
+           [array           int 8              'message' count 'messageSize - 24']
        ]
     ]
 ]
diff --git a/protocols/opcua/src/main/xslt/opc-types.xsl b/protocols/opcua/src/main/xslt/opc-types.xsl
index ee44a6d..2dafce0 100644
--- a/protocols/opcua/src/main/xslt/opc-types.xsl
+++ b/protocols/opcua/src/main/xslt/opc-types.xsl
@@ -67,6 +67,8 @@
         <xsl:apply-templates select="$file/node:UANodeSet/node:UADataType[@BrowseName='WriteResponse']"/>
         <xsl:apply-templates select="$file/node:UANodeSet/node:UADataType[@BrowseName='BrowseRequest']"/>
         <xsl:apply-templates select="$file/node:UANodeSet/node:UADataType[@BrowseName='BrowseResponse']"/>
+        <xsl:apply-templates select="$file/node:UANodeSet/node:UADataType[@BrowseName='GetEndpointsRequest']"/>
+        <xsl:apply-templates select="$file/node:UANodeSet/node:UADataType[@BrowseName='GetEndpointsResponse']"/>
         <xsl:apply-templates select="$file/node:UANodeSet/node:UADataType[@BrowseName='ServiceFault']"/>
 
     ['473' CloseSessionRequest
@@ -434,7 +436,7 @@
     [simple PascalString 'gatewayServerUri']
     [simple PascalString 'discoveryProfileUri']
     [simple int 32 'noOfDiscoveryUrls']
-    [optional PascalString 'discoveryUrls' 'noOfDiscoveryUrls > 0']
+    [array PascalString 'discoveryUrls' count 'noOfDiscoveryUrls']
 ]
 
 [type 'EndpointDescription'