@@ -311,9 +311,12 @@ public static byte[] FormatStringLiteral(byte[] bytes, bool unicode, bool prefix
311311
312312 Debug . Assert ( ! unicode || bytes . Length % 2 == 0 , "Odd number of bytes in Unicode string." ) ;
313313
314+ byte [ ] originalBytes = null ;
315+
314316 bool encrypted = false ;
315- if ( securityHandler != null )
317+ if ( securityHandler != null && ! hex )
316318 {
319+ originalBytes = bytes ;
317320 bytes = ( byte [ ] ) bytes . Clone ( ) ;
318321 bytes = securityHandler . EncryptBytes ( bytes ) ;
319322 encrypted = true ;
@@ -403,23 +406,58 @@ public static byte[] FormatStringLiteral(byte[] bytes, bool unicode, bool prefix
403406 }
404407 else
405408 {
406- Hex :
409+ // Hex:
407410 if ( hex )
408411 {
409- pdf . Append ( prefix ? "<FEFF" : "<" ) ;
410- for ( int idx = 0 ; idx < count ; idx += 2 )
412+ if ( securityHandler != null && prefix )
411413 {
412- pdf . AppendFormat ( "{0:X2}{1:X2}" , bytes [ idx ] , bytes [ idx + 1 ] ) ;
413- if ( idx != 0 && ( idx % 48 ) == 0 )
414- pdf . Append ( "\n " ) ;
414+ // TODO Reduce redundancy.
415+ // Encrypt data after padding BOM.
416+ var bytes2 = new byte [ bytes . Length + 2 ] ;
417+ // Add BOM.
418+ bytes2 [ 0 ] = 0xfe ;
419+ bytes2 [ 1 ] = 0xff ;
420+ // Copy bytes.
421+ Array . Copy ( bytes , 0 , bytes2 , 2 , bytes . Length ) ;
422+ // Encyption.
423+ bytes2 = securityHandler . EncryptBytes ( bytes2 ) ;
424+ encrypted = true ;
425+ pdf . Append ( "<" ) ;
426+ var count2 = bytes2 . Length ;
427+ for ( int idx = 0 ; idx < count2 ; idx += 2 )
428+ {
429+ pdf . AppendFormat ( "{0:X2}{1:X2}" , bytes2 [ idx ] , bytes2 [ idx + 1 ] ) ;
430+ if ( idx != 0 && ( idx % 48 ) == 0 )
431+ pdf . Append ( "\n " ) ;
432+ }
433+ pdf . Append ( ">" ) ;
434+ }
435+ else
436+ {
437+ // No prefix or no encryption.
438+ pdf . Append ( prefix ? "<FEFF" : "<" ) ;
439+ for ( int idx = 0 ; idx < count ; idx += 2 )
440+ {
441+ pdf . AppendFormat ( "{0:X2}{1:X2}" , bytes [ idx ] , bytes [ idx + 1 ] ) ;
442+ if ( idx != 0 && ( idx % 48 ) == 0 )
443+ pdf . Append ( "\n " ) ;
444+ }
445+ pdf . Append ( ">" ) ;
415446 }
416- pdf . Append ( ">" ) ;
417447 }
418448 else
419449 {
420450 // TODO non hex literals... not sure how to treat linefeeds, '(', '\' etc.
421- hex = true ;
422- goto Hex ;
451+ if ( encrypted )
452+ {
453+ // Hack: Call self with hex := true.
454+ return FormatStringLiteral ( originalBytes , unicode , prefix , true , securityHandler ) ;
455+ }
456+ else
457+ {
458+ Debug . Assert ( false , "Test if this code can be invoked." ) ;
459+ return FormatStringLiteral ( bytes , true , prefix , true , null ) ;
460+ }
423461 }
424462 }
425463 return RawEncoding . GetBytes ( pdf . ToString ( ) ) ;
0 commit comments