Added integer overflow checks to toSvgString() in Java, C++, Rust code; added checks to toImage() in Java code.

This commit is contained in:
Project Nayuki 2018-02-26 20:29:25 +00:00
parent 6a71979c2a
commit 9728f19f59
3 changed files with 11 additions and 2 deletions

View File

@ -157,6 +157,9 @@ bool QrCode::getModule(int x, int y) const {
std::string QrCode::toSvgString(int border) const {
if (border < 0)
throw "Border must be non-negative";
if (border > INT_MAX / 2 || border * 2 > INT_MAX - size)
throw "Border too large";
std::ostringstream sb;
sb << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
sb << "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n";

View File

@ -258,6 +258,9 @@ public final class QrCode {
public BufferedImage toImage(int scale, int border) {
if (scale <= 0 || border < 0)
throw new IllegalArgumentException("Value out of range");
if (border > Integer.MAX_VALUE / 2 || size + border * 2L > Integer.MAX_VALUE / scale)
throw new IllegalArgumentException("Scale or border too large");
BufferedImage result = new BufferedImage((size + border * 2) * scale, (size + border * 2) * scale, BufferedImage.TYPE_INT_RGB);
for (int y = 0; y < result.getHeight(); y++) {
for (int x = 0; x < result.getWidth(); x++) {
@ -279,6 +282,9 @@ public final class QrCode {
public String toSvgString(int border) {
if (border < 0)
throw new IllegalArgumentException("Border must be non-negative");
if (size + border * 2L > Integer.MAX_VALUE)
throw new IllegalArgumentException("Border too large");
StringBuilder sb = new StringBuilder();
sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
sb.append("<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n");

View File

@ -240,9 +240,9 @@ impl QrCode {
let mut result: String = String::new();
result.push_str("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
result.push_str("<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n");
let dimension = self.size.checked_add(border.checked_mul(2).unwrap()).unwrap();
result.push_str(&format!(
"<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" viewBox=\"0 0 {0} {0}\" stroke=\"none\">\n",
self.size + border * 2));
"<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" viewBox=\"0 0 {0} {0}\" stroke=\"none\">\n", dimension));
result.push_str("\t<rect width=\"100%\" height=\"100%\" fill=\"#FFFFFF\"/>\n");
result.push_str("\t<path d=\"");
let mut head: bool = true;