33import java .nio .ByteBuffer ;
44
55public class PolicyInfo {
6+ private static final int DEFAULT_BINDING_SIZE = 8 ;
67 private NanoTDFType .PolicyType type ;
7- private boolean hasECDSABinding ;
88 private byte [] body ;
99 private byte [] binding ;
1010
@@ -13,7 +13,6 @@ public PolicyInfo() {
1313
1414 public PolicyInfo (ByteBuffer buffer , ECCMode eccMode ) {
1515 this .type = NanoTDFType .PolicyType .values ()[buffer .get ()];
16- this .hasECDSABinding = eccMode .isECDSABindingEnabled ();
1716
1817 if (this .type == NanoTDFType .PolicyType .REMOTE_POLICY ) {
1918
@@ -45,13 +44,39 @@ public PolicyInfo(ByteBuffer buffer, ECCMode eccMode) {
4544 }
4645 }
4746
48- int bindingBytesSize = 8 ; // GMAC length
49- if (this .hasECDSABinding ) { // ECDSA - The size of binding depends on the curve.
50- bindingBytesSize = ECCMode .getECDSASignatureStructSize (eccMode .getCurve ());
47+ this .binding = readBinding (buffer , eccMode );
48+ }
49+
50+ static byte [] readBinding (ByteBuffer buffer , ECCMode eccMode ) {
51+ byte [] binding ;
52+ if (eccMode .isECDSABindingEnabled ()) { // ECDSA - The size of binding depends on the curve.
53+ int rSize = getSize (buffer .get (), eccMode .getCurve ());
54+ // don't bother to validate since we can only create an array of size 1024 bytes
55+ byte [] rBytes = new byte [rSize ];
56+ buffer .get (rBytes );
57+ int sSize = getSize (buffer .get (), eccMode .getCurve ());
58+ byte [] sBytes = new byte [sSize ];
59+ buffer .get (sBytes );
60+ int bindingByteSize = eccMode .getCurve ().getKeySize ();
61+ binding = new byte [2 * bindingByteSize ];
62+ System .arraycopy (rBytes , 0 , binding , bindingByteSize - rSize , rSize );
63+ System .arraycopy (sBytes , 0 , binding , bindingByteSize + bindingByteSize - sSize , sSize );
64+ } else {
65+ binding = new byte [DEFAULT_BINDING_SIZE ];
66+ buffer .get (binding );
5167 }
5268
53- this .binding = new byte [bindingBytesSize ];
54- buffer .get (this .binding );
69+ return binding ;
70+ }
71+
72+ private static int getSize (byte size , NanoTDFType .ECCurve curve ) {
73+ int elementSize = Byte .toUnsignedInt (size );
74+ if (elementSize > curve .getKeySize ()) {
75+ throw new SDK .MalformedTDFException (
76+ String .format ("Invalid ECDSA binding size. Expected signature components to be at most %d bytes but got (%d) bytes for curve %s." ,
77+ curve .getKeySize (), elementSize , curve .getCurveName ()));
78+ }
79+ return elementSize ;
5580 }
5681
5782 public int getTotalSize () {
@@ -64,7 +89,6 @@ public int getTotalSize() {
6489 if (type == NanoTDFType .PolicyType .EMBEDDED_POLICY_PLAIN_TEXT ||
6590 type == NanoTDFType .PolicyType .EMBEDDED_POLICY_ENCRYPTED ) {
6691
67- int policySize = body .length ;
6892 totalSize = (1 + Short .BYTES + body .length + binding .length );
6993 } else {
7094 throw new RuntimeException ("Embedded policy with key access is not supported." );
0 commit comments