public Request protectRequest ( Request request ) throws IOException { try { Request result = request . newBuilder ( ) . header ( AUTHENTICATE , BEARER_TOKEP_REFIX + clientSecurityToken ) . build ( ) ; if ( ! supportsProtection ( ) ) { return result ; } Buffer buffer = new Buffer ( ) ; request . body ( ) . writeTo ( buffer ) ; String currentbody = buffer . readUtf8 ( ) ; if ( currentbody == null || currentbody . length ( ) == 0 ) { return result ; } JsonWebKey clientPublicEncryptionKey = MessageSecurityHelper . getJwkWithPublicKeyOnly ( clientEncryptionKey ) ; String payload = currentbody . substring ( 0 , currentbody . length ( ) - 1 ) + ",\"rek\":{\"jwk\":" + clientPublicEncryptionKey . toString ( ) + "}}" ; JWEObject jweObject = protectPayload ( payload ) ; JWSHeader jwsHeader = new JWSHeader ( "RS256" , clientSignatureKey . kid ( ) , clientSecurityToken , getCurrentTimestamp ( ) , "PoP" , null ) ; String jwsHeaderJsonb64 = MessageSecurityHelper . stringToBase64Url ( jwsHeader . serialize ( ) ) ; String protectedPayload = MessageSecurityHelper . stringToBase64Url ( jweObject . serialize ( ) ) ; byte [ ] data = ( jwsHeaderJsonb64 + "." + protectedPayload ) . getBytes ( MESSAGE_ENCODING ) ; RsaKey clientSignatureRsaKey = new RsaKey ( clientSignatureKey . kid ( ) , clientSignatureKey . toRSA ( true ) ) ; Pair < byte [ ] , String > signature = clientSignatureRsaKey . signAsync ( getSha256 ( data ) , "RS256" ) . get ( ) ; JWSObject jwsObject = new JWSObject ( jwsHeader , protectedPayload , MessageSecurityHelper . bytesToBase64Url ( signature . getKey ( ) ) ) ; RequestBody body = RequestBody . create ( MediaType . parse ( "application/jose+json" ) , jwsObject . serialize ( ) ) ; return result . newBuilder ( ) . method ( request . method ( ) , body ) . build ( ) ; } catch ( ExecutionException e ) { // unexpected; return null ; } catch ( InterruptedException e ) { // unexpected; return null ; } catch ( NoSuchAlgorithmException e ) { // unexpected; return null ; } }
Protects existing request . Replaces its body with encrypted version .