Path: blob/master/test/jdk/com/sun/crypto/provider/Cipher/DES/KeyWrapping.java
41161 views
/*1* Copyright (c) 1999, 2007, 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 000000026* @summary KeyWrapping27* @author Jan Luehe28*/29import javax.crypto.*;30import java.security.*;3132public class KeyWrapping {3334public static void main(String[] args) throws Exception {35Cipher c1 = Cipher.getInstance("DES", "SunJCE");36Cipher c2 = Cipher.getInstance("DES");3738KeyGenerator keyGen = KeyGenerator.getInstance("DES");39keyGen.init(56);4041// Generate two DES keys: sKey and sessionKey42SecretKey sKey = keyGen.generateKey();43SecretKey sessionKey = keyGen.generateKey();4445// wrap and unwrap the session key46// make sure the unwrapped session key47// can decrypt a message encrypted48// with the session key49c1.init(Cipher.WRAP_MODE, sKey);5051byte[] wrappedKey = c1.wrap(sessionKey);5253c1.init(Cipher.UNWRAP_MODE, sKey);5455SecretKey unwrappedSessionKey =56(SecretKey)c1.unwrap(wrappedKey, "DES",57Cipher.SECRET_KEY);5859c2.init(Cipher.ENCRYPT_MODE, unwrappedSessionKey);6061String msg = "Hello";6263byte[] cipherText = c2.doFinal(msg.getBytes());6465c2.init(Cipher.DECRYPT_MODE, unwrappedSessionKey);6667byte[] clearText = c2.doFinal(cipherText);6869if (!msg.equals(new String(clearText)))70throw new Exception("The unwrapped session key is corrupted.");7172KeyPairGenerator kpairGen = KeyPairGenerator.getInstance("DSA");73kpairGen.initialize(1024);7475KeyPair kpair = kpairGen.genKeyPair();7677PublicKey pub = kpair.getPublic();78PrivateKey pri = kpair.getPrivate();7980c1.init(Cipher.WRAP_MODE, sKey);8182byte[] wrappedPub = c1.wrap(pub);83byte[] wrappedPri = c1.wrap(pri);8485c1.init(Cipher.UNWRAP_MODE, sKey);8687Key unwrappedPub = c1.unwrap(wrappedPub, "DSA",88Cipher.PUBLIC_KEY);89Key unwrappedPri = c1.unwrap(wrappedPri, "DSA",90Cipher.PRIVATE_KEY);91}92}939495