private Url encryptUrl(final Url url) { if (url.getSegments().isEmpty() && url.getQueryParameters().isEmpty()) { return url; } final String encryptedUrlString = this.getCrypt().encryptUrlSafe(url.toString()); final Url encryptedUrl = new Url(url.getCharset()); encryptedUrl.getSegments().add(encryptedUrlString); final int numberOfSegments = url.getSegments().size(); final HashedSegmentGenerator generator = new HashedSegmentGenerator(encryptedUrlString); for (int segNo = 0; segNo < numberOfSegments; ++segNo) { encryptedUrl.getSegments().add(generator.next()); } return encryptedUrl; }
private Url decryptUrl(final Request request, final Url encryptedUrl) { if (encryptedUrl.getSegments().isEmpty()) { return encryptedUrl; } final List<String> encryptedSegments = (List<String>) encryptedUrl.getSegments(); if (encryptedSegments.size() < 1) { return null; } Url url = new Url(request.getCharset()); try { final String encryptedUrlString = (String) encryptedSegments.get(0); if (Strings.isEmpty((CharSequence) encryptedUrlString)) { return null; } final String decryptedUrl = this.getCrypt().decryptUrlSafe(encryptedUrlString); if (decryptedUrl == null) { return null; } final Url originalUrl = Url.parse(decryptedUrl, request.getCharset()); final int originalNumberOfSegments = originalUrl.getSegments().size(); final int encryptedNumberOfSegments = encryptedUrl.getSegments().size(); final HashedSegmentGenerator generator = new HashedSegmentGenerator(encryptedUrlString); int segNo; for (segNo = 1; segNo < encryptedNumberOfSegments; ++segNo) { if (segNo > originalNumberOfSegments) { break; } final String next = generator.next(); final String encryptedSegment = (String) encryptedSegments.get(segNo); if (!next.equals(encryptedSegment)) { break; } url.getSegments().add(originalUrl.getSegments().get(segNo - 1)); } while (segNo < encryptedNumberOfSegments) { url.getSegments().add(encryptedUrl.getSegments().get(segNo)); ++segNo; } url.getQueryParameters().addAll(originalUrl.getQueryParameters()); } catch (Exception e) { CryptoMapper.log.error("Error decrypting URL", e); url = null; } return url; }