/* * Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* @test * @bug 4102896 * @summary Make sure that a SecureRandom object can be serialized */ import java.security.*; import java.io.*; public class Serialize { public static void main(String args[]) throws Exception { for (String alg: new String[]{ "SHA1PRNG", "DRBG", "Hash_DRBG", "HMAC_DRBG", "CTR_DRBG"}) { System.out.println("Testing " + alg); // Even unseeded object can be serialized and deserialized SecureRandom s1 = getInstance(alg); revive(s1).nextInt(); if (alg.contains("DRBG")) { revive(s1).reseed(); } // After seeded, deserialized object should emit same random data s1 = getInstance(alg); s1.nextInt(); // state set SecureRandom s2 = revive(s1); int n1 = s1.nextInt(); int n2 = s2.nextInt(); if (n1 != n2) { throw new Exception(); } // Or seeded with user-provided data s1.setSeed(42); s2.setSeed(42); n1 = s1.nextInt(); n2 = s2.nextInt(); if (n1 != n2) { throw new Exception(); } // But not after automatic reseed if (alg.contains("DRBG")) { s1.reseed(); s2.reseed(); n1 = s1.nextInt(); n2 = s2.nextInt(); if (n1 == n2) { throw new Exception(); } } } } private static SecureRandom getInstance(String alg) throws Exception { if (alg.equals("SHA1PRNG") || alg.equals("DRBG")) { return SecureRandom.getInstance(alg); } else { String old = Security.getProperty("drbg"); try { Security.setProperty("drbg", alg); return SecureRandom.getInstance("DRBG"); } finally { Security.setProperty("drbg", old); } } } private static SecureRandom revive(SecureRandom sr) throws Exception { ByteArrayOutputStream bout = new ByteArrayOutputStream(); new ObjectOutputStream(bout).writeObject(sr); return (SecureRandom) new ObjectInputStream( new ByteArrayInputStream(bout.toByteArray())).readObject(); } }