@@ -82,6 +82,11 @@ impl PreSharedKey {
8282 . expect ( "shake128 failed" ) ;
8383 Fingerprint ( out)
8484 }
85+
86+ /// Export this key in key file format compatible with go-libp2p.
87+ pub fn to_key_file ( self ) -> String {
88+ format ! ( "/key/swarm/psk/1.0.0/\n /base16/\n {}\n " , to_hex( & self . 0 ) )
89+ }
8590}
8691
8792fn parse_hex_key ( s : & str ) -> Result < [ u8 ; KEY_SIZE ] , KeyParseError > {
@@ -130,8 +135,8 @@ impl FromStr for PreSharedKey {
130135
131136impl fmt:: Debug for PreSharedKey {
132137 fn fmt ( & self , f : & mut fmt:: Formatter < ' _ > ) -> fmt:: Result {
133- f. debug_tuple ( "PreSharedKey" )
134- . field ( & to_hex ( & self . 0 ) )
138+ f. debug_struct ( "PreSharedKey" )
139+ . field ( "fingerprint" , & self . fingerprint ( ) . to_string ( ) )
135140 . finish ( )
136141 }
137142}
@@ -343,6 +348,19 @@ mod tests {
343348 . quickcheck ( prop as fn ( PreSharedKey ) -> _ ) ;
344349 }
345350
351+ #[ test]
352+ fn psk_to_key_file_parse ( ) {
353+ fn prop ( key : PreSharedKey ) -> bool {
354+ let text = key. to_key_file ( ) ;
355+ text. parse :: < PreSharedKey > ( )
356+ . map ( |res| res == key)
357+ . unwrap_or ( false )
358+ }
359+ QuickCheck :: new ( )
360+ . tests ( 10 )
361+ . quickcheck ( prop as fn ( PreSharedKey ) -> _ ) ;
362+ }
363+
346364 #[ test]
347365 fn psk_parse_failure ( ) {
348366 use KeyParseError :: * ;
@@ -373,4 +391,34 @@ mod tests {
373391 let actual = key. fingerprint ( ) . to_string ( ) ;
374392 assert_eq ! ( expected, actual) ;
375393 }
394+
395+ #[ test]
396+ fn debug_formatting_does_not_leak_raw_psk ( ) {
397+ let raw_hex = "6189c5cf0b87fb800c1a9feeda73c6ab5e998db48fb9e6a978575c770ceef683" ;
398+ let key = format ! ( "/key/swarm/psk/1.0.0/\n /base16/\n {raw_hex}" )
399+ . parse :: < PreSharedKey > ( )
400+ . unwrap ( ) ;
401+ let fingerprint = key. fingerprint ( ) . to_string ( ) ;
402+
403+ let debug_output = format ! ( "{key:?}" ) ;
404+ let config_debug_output = format ! ( "{:?}" , PnetConfig :: new( key) ) ;
405+
406+ assert ! ( !debug_output. contains( raw_hex) ) ;
407+ assert ! ( !config_debug_output. contains( raw_hex) ) ;
408+ assert ! ( debug_output. contains( & fingerprint) ) ;
409+ assert ! ( config_debug_output. contains( & fingerprint) ) ;
410+ }
411+
412+ #[ test]
413+ fn key_file_export_contains_raw_psk ( ) {
414+ let raw_hex = "6189c5cf0b87fb800c1a9feeda73c6ab5e998db48fb9e6a978575c770ceef683" ;
415+ let key = format ! ( "/key/swarm/psk/1.0.0/\n /base16/\n {raw_hex}" )
416+ . parse :: < PreSharedKey > ( )
417+ . unwrap ( ) ;
418+
419+ let key_file = key. to_key_file ( ) ;
420+
421+ assert ! ( key_file. contains( raw_hex) ) ;
422+ assert_eq ! ( key_file. parse:: <PreSharedKey >( ) . unwrap( ) , key) ;
423+ }
376424}
0 commit comments