@@ -20,16 +20,19 @@ final class Encryption
2020 const MAX_PAYLOAD_LENGTH = 4078 ;
2121
2222 /**
23- * @param $payload
24- * @return string
23+ * @param string $payload
24+ * @param bool $automatic
25+ * @return string padded payload (plaintext)
2526 */
26- public static function automaticPadding ($ payload )
27+ public static function padPayload ($ payload, $ automatic )
2728 {
28- return str_pad ($ payload , self ::MAX_PAYLOAD_LENGTH , chr (0 ), STR_PAD_LEFT );
29+ $ payloadLen = strlen ($ payload );
30+ $ padLen = $ automatic ? self ::MAX_PAYLOAD_LENGTH - $ payloadLen : 0 ;
31+ return chr ($ padLen >> 8 ).chr ($ padLen & 0xFF ).str_pad ($ payload , $ padLen + $ payloadLen , chr (0 ), STR_PAD_LEFT );
2932 }
3033
3134 /**
32- * @param string $payload
35+ * @param string $payload With padding
3336 * @param string $userPublicKey MIME base 64 encoded
3437 * @param string $userAuthToken MIME base 64 encoded
3538 * @param bool $nativeEncryption Use OpenSSL (>PHP7.1)
@@ -40,7 +43,6 @@ public static function encrypt($payload, $userPublicKey, $userAuthToken, $native
4043 {
4144 $ userPublicKey = base64_decode ($ userPublicKey );
4245 $ userAuthToken = base64_decode ($ userAuthToken );
43- $ plaintext = chr (0 ).chr (0 ).$ payload ;
4446
4547 // initialize utilities
4648 $ math = EccFactory::getAdapter ();
@@ -82,9 +84,9 @@ public static function encrypt($payload, $userPublicKey, $userAuthToken, $native
8284 // encrypt
8385 // "The additional data passed to each invocation of AEAD_AES_128_GCM is a zero-length octet sequence."
8486 if (!$ nativeEncryption ) {
85- list ($ encryptedText , $ tag ) = \Jose \Util \GCM ::encrypt ($ contentEncryptionKey , $ nonce , $ plaintext , "" );
87+ list ($ encryptedText , $ tag ) = \Jose \Util \GCM ::encrypt ($ contentEncryptionKey , $ nonce , $ payload , "" );
8688 } else {
87- $ encryptedText = openssl_encrypt ($ plaintext , 'aes-128-gcm ' , $ contentEncryptionKey , OPENSSL_RAW_DATA , $ nonce , $ tag ); // base 64 encoded
89+ $ encryptedText = openssl_encrypt ($ payload , 'aes-128-gcm ' , $ contentEncryptionKey , OPENSSL_RAW_DATA , $ nonce , $ tag ); // base 64 encoded
8890 }
8991
9092 // return values in url safe base64
0 commit comments