Path: blob/master/test/jdk/sun/security/provider/DSA/TestMaxLengthDER.java
41154 views
/*1* Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223/*24* @test25* @bug 818359126* @summary Test decoding of DER length fields containing Integer.MAX_VALUE27* @run main TestMaxLengthDER28*/2930import java.io.*;31import java.math.*;32import java.security.*;33import java.security.spec.*;3435public class TestMaxLengthDER {3637public static void main(String[] args) throws Exception {3839String message = "Message";40Signature sig = Signature.getInstance("SHA256withDSA");41KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA");42SecureRandom rnd = new SecureRandom();43rnd.setSeed(1);44kpg.initialize(2048, rnd);45KeyPair kp = kpg.generateKeyPair();46sig.initSign(kp.getPrivate());47sig.update(message.getBytes());48byte[] sigData = sig.sign();4950// Set the length of the second integer to Integer.MAX_VALUE51// First copy all the signature data to the correct location52int lengthPos = sigData[3] + 5;53byte[] modifiedSigData = new byte[sigData.length + 4];54System.arraycopy(sigData, 0, modifiedSigData, 0, lengthPos);55System.arraycopy(sigData, lengthPos + 1, modifiedSigData,56lengthPos + 5, sigData.length - (lengthPos + 1));5758// Increase the length (in bytes) of the sequence to account for59// the larger length field60modifiedSigData[1] += 4;6162// Modify the length field63modifiedSigData[lengthPos] = (byte) 0x84;64modifiedSigData[lengthPos + 1] = (byte) 0x7F;65modifiedSigData[lengthPos + 2] = (byte) 0xFF;66modifiedSigData[lengthPos + 3] = (byte) 0xFF;67modifiedSigData[lengthPos + 4] = (byte) 0xFF;6869sig.initVerify(kp.getPublic());70sig.update(message.getBytes());7172try {73sig.verify(modifiedSigData);74throw new RuntimeException("No exception on misencoded signature");75} catch (SignatureException ex) {76if (ex.getCause() instanceof EOFException) {77// this is expected78} else {79throw ex;80}81}82}83}848586