Tracy
Tracy

Reputation: 3

Java Hitting SSLHandshakeException when trying to read image URL

I was trying to get image from an URL, e.g. https://localhost:8443/image/01/example.png and then draw a string on it. However, I always hit SSLHandshakeException if I did not disable SSL certificate checking, below is my code with disableSSLCertificateChecking():

private String drawTextOnImage(String imagePath, String rate, String lastUpdatedDate) throws Exception {
        URL url = new URL(imagePath);
        // Fetch the image from the URL
        BufferedImage image = null;
        try {
            disableSSLCertificateChecking();
            image = ImageIO.read (url.openStream());
            // Continue processing
        } catch (Exception e) {
            logger.error("Error loading image from URL: " + imagePath, e);
            throw new Exception("Failed to load image", e);
        }
        // Get the graphics object from image
        Graphics2D g = (Graphics2D) image.getGraphics();
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        //Draw auto sweep rate
        g.setFont(new Font("Times New Roman", Font.BOLD, 110)); // Set font size and style
        g.setColor(new Color(24, 59, 155)); // Set text color
        g.drawString(rate, 100, 526);

        // Draw last updated date
        g.setFont(new Font("Times New Roman", Font.ITALIC, 30)); // You can set a different font for the second text
        g.setColor(Color.WHITE); // You can set a different color for the second text
        g.drawString(lastUpdatedDate, 100, 600);
        g.dispose();

        // Convert the modified image to a byte array
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "png", baos);
        byte[] imageBytes = baos.toByteArray();

        // Encode the byte array to Base64 string
        return Base64.getEncoder().encodeToString(imageBytes);

    }

private void disableSSLCertificateChecking() throws Exception {
        TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }
                    public void checkClientTrusted(X509Certificate[] certs, String authType) { }
                    public void checkServerTrusted(X509Certificate[] certs, String authType) { }
                }
        };

        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        // Optional: Disable hostname verification as well
        HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> true);
    }

Is there any workaround without disabling the SSL check that able to perform read and draw on the image?

Upvotes: 0

Views: 36

Answers (0)

Related Questions