11using System ;
2+ using System . Text ;
23
34namespace Padding_Oracle_Attack
45{
@@ -17,11 +18,45 @@ public static void Main()
1718
1819 Console . WriteLine ( "Plaintext:\n {0}" , hiddenMessage ) ;
1920 Console . WriteLine ( "\n Ciphertext:\n {0}" , String . Join ( "\n " , blocks . ConvertAll ( block => Convert . ToBase64String ( block ) ) ) ) ;
20- Console . WriteLine ( "\n Attack results:\n TODO " ) ;
21+ Console . WriteLine ( "\n Attack results:" ) ;
2122
22- encrypted [ encrypted . Length - 1 ] = 22 ;
23+ for ( int blockIndex = 1 ; blockIndex < blocks . Count ; ++ blockIndex )
24+ {
25+ Console . WriteLine ( DecryptBlock ( blocks [ blockIndex ] , blocks [ blockIndex - 1 ] ) ) ;
26+ }
27+ }
28+
29+ private static string DecryptBlock ( byte [ ] block , byte [ ] previousBlock )
30+ {
31+ byte [ ] decrypted = new byte [ block . Length ] ;
32+ byte [ ] manipulatedPrevious = new byte [ 16 ] ;
33+
34+ // in case of PKCS7 padding value is same as padding length
35+ for ( int paddingLength = 1 ; paddingLength <= block . Length ; ++ paddingLength )
36+ {
37+ for ( int pos = block . Length - 1 ; pos >= block . Length - paddingLength ; -- pos )
38+ {
39+ int previousPaddingLength = paddingLength - 1 ;
40+ manipulatedPrevious [ pos ] ^= ( byte ) ( previousPaddingLength ^ paddingLength ) ;
41+ }
42+ var found = false ;
43+ for ( byte v = byte . MinValue ; v <= byte . MaxValue ; ++ v )
44+ {
45+ manipulatedPrevious [ block . Length - paddingLength ] = v ;
46+ if ( server . IsPaddingCorrect ( concat ( manipulatedPrevious , block ) ) )
47+ {
48+ found = true ;
49+ decrypted [ block . Length - paddingLength ] = ( byte ) ( previousBlock [ block . Length - paddingLength ] ^ paddingLength ^ v ) ;
50+ break ;
51+ }
52+ }
53+ if ( ! found )
54+ {
55+ throw new Exception ( "Decryption not possible. This function supports only AES/CBC/PKCS7" ) ;
56+ }
57+ }
2358
24- Console . WriteLine ( " \n Padding is {0}" , server . IsPaddingCorrect ( encrypted ) ? "correct" : "incorrect" ) ;
59+ return Encoding . UTF8 . GetString ( decrypted , 0 , decrypted . Length ) ;
2560 }
2661 }
2762}
0 commit comments