NegativeLength.java revision 16177:89ef4b822745
1/*
2 * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 */
23
24/*
25 * @test
26 * @bug 8001596
27 * @modules java.base/javax.crypto.spec:open
28 * @summary Incorrect condition check in PBKDF2KeyImpl.java
29 */
30
31import java.security.*;
32import java.security.spec.*;
33import javax.crypto.*;
34import javax.crypto.spec.*;
35import java.lang.reflect.*;
36
37public class NegativeLength {
38
39    public static void main(String[] args) throws Exception {
40        SecretKeyFactory skf = SecretKeyFactory.getInstance(
41            "PBKDF2WithHmacSHA1", "SunJCE");
42
43        // Create a valid PBEKeySpec
44        PBEKeySpec pbeks = new PBEKeySpec(
45            new char['p'], new byte[1], 1024, 8);
46
47        // Use reflection to set it negative.
48        Class c = pbeks.getClass();
49        Field f = c.getDeclaredField("keyLength");
50        f.setAccessible(true);
51        f.setInt(pbeks, -8);
52
53        System.out.println("pbeks.getKeyLength(): " + pbeks.getKeyLength());
54
55        try {
56
57            // A negative length is clearly wrong, we should get a
58            // InvalidKeySpecException.  Anything else is wrong.
59            skf.generateSecret(pbeks);
60            throw new Exception("We shouldn't get here.");
61        } catch (InvalidKeySpecException ike) {
62            // swallow, this is the exception we want.
63            System.out.println("Test Passed.");
64        }
65    }
66}
67
68