private void testCipherNameWithWrap(String name, String simpleName) throws Exception { KeyGenerator kg = KeyGenerator.getInstance("AES"); kg.init(new SecureRandom()); SecretKey key = kg.generateKey(); byte[] salt = { (byte) 0xc7, (byte) 0x73, (byte) 0x21, (byte) 0x8c, (byte) 0x7e, (byte) 0xc8, (byte) 0xee, (byte) 0x99 }; char[] password = {'p', 'a', 's', 's', 'w', 'o', 'r', 'd'}; PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, 20); PBEKeySpec pbeKeySpec = new PBEKeySpec(password); SecretKeyFactory keyFac = SecretKeyFactory.getInstance(name); SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec); Cipher pbeEncryptCipher = Cipher.getInstance(name, "SC"); pbeEncryptCipher.init(Cipher.WRAP_MODE, pbeKey, pbeParamSpec); byte[] symKeyBytes = pbeEncryptCipher.wrap(key); Cipher simpleCipher = Cipher.getInstance(simpleName, "SC"); simpleCipher.init(Cipher.UNWRAP_MODE, pbeKey, pbeParamSpec); SecretKey unwrappedKey = (SecretKey) simpleCipher.unwrap(symKeyBytes, "AES", Cipher.SECRET_KEY); if (!Arrays.areEqual(unwrappedKey.getEncoded(), key.getEncoded())) { fail("key mismatch on unwrapping"); } }
/** * 使用指定的公钥初始化加密器,并对密钥进行加密。 * * @param cipher 加密器。 * @param publicKey 公钥。 * @param key 加密密钥。 * @return 加密后的数据。 */ public static byte[] wrap(Cipher cipher, PublicKey publicKey, Key key) { try { cipher.init(Cipher.WRAP_MODE, publicKey); return cipher.wrap(key); } catch (Exception e) { throw new CryptoException(e.getMessage(), e); } }
public ASN1Sequence generateRecipientEncryptedKeys( AlgorithmIdentifier keyAgreeAlgorithm, AlgorithmIdentifier keyEncryptionAlgorithm, GenericKey contentEncryptionKey) throws CMSException { init(keyAgreeAlgorithm.getAlgorithm()); PrivateKey senderPrivateKey = this.senderPrivateKey; ASN1ObjectIdentifier keyAgreementOID = keyAgreeAlgorithm.getAlgorithm(); if (keyAgreementOID.getId().equals(CMSEnvelopedGenerator.ECMQV_SHA1KDF)) { senderPrivateKey = new MQVPrivateKeySpec( senderPrivateKey, ephemeralKP.getPrivate(), ephemeralKP.getPublic()); } ASN1EncodableVector recipientEncryptedKeys = new ASN1EncodableVector(); for (int i = 0; i != recipientIDs.size(); i++) { PublicKey recipientPublicKey = (PublicKey) recipientKeys.get(i); KeyAgreeRecipientIdentifier karId = (KeyAgreeRecipientIdentifier) recipientIDs.get(i); if (keyAgreementOID.getId().equals(CMSEnvelopedGenerator.ECMQV_SHA1KDF)) { recipientPublicKey = new MQVPublicKeySpec(recipientPublicKey, recipientPublicKey); } try { // Use key agreement to choose a wrap key for this recipient KeyAgreement keyAgreement = helper.createKeyAgreement(keyAgreementOID); keyAgreement.init(senderPrivateKey, random); keyAgreement.doPhase(recipientPublicKey, true); SecretKey keyEncryptionKey = keyAgreement.generateSecret(keyEncryptionAlgorithm.getAlgorithm().getId()); // Wrap the content encryption key with the agreement key Cipher keyEncryptionCipher = helper.createCipher(keyEncryptionAlgorithm.getAlgorithm()); keyEncryptionCipher.init(Cipher.WRAP_MODE, keyEncryptionKey, random); byte[] encryptedKeyBytes = keyEncryptionCipher.wrap(helper.getJceKey(contentEncryptionKey)); ASN1OctetString encryptedKey = new DEROctetString(encryptedKeyBytes); recipientEncryptedKeys.add(new RecipientEncryptedKey(karId, encryptedKey)); } catch (GeneralSecurityException e) { throw new CMSException("cannot perform agreement step: " + e.getMessage(), e); } } return new DERSequence(recipientEncryptedKeys); }
public byte[] generateWrappedKey(GenericKey encryptionKey) throws OperatorException { Key contentEncryptionKeySpec = OperatorUtils.getJceKey(encryptionKey); Cipher keyEncryptionCipher = helper.createSymmetricWrapper(this.getAlgorithmIdentifier().getAlgorithm()); try { keyEncryptionCipher.init(Cipher.WRAP_MODE, wrappingKey, random); return keyEncryptionCipher.wrap(contentEncryptionKeySpec); } catch (InvalidKeyException e) { throw new OperatorException("cannot wrap key: " + e.getMessage(), e); } catch (GeneralSecurityException e) { throw new OperatorException("cannot wrap key: " + e.getMessage(), e); } }
/** * Wraps a secretkey * * @param wrappedKey The wrapped session key * @param wrappingTransformation The wrapping transformation associated with this operation * @param wrappingKey The wrapping key * @param wrappedKeyAlgorithm The wrapped key Algorithim * @return The unwrapped session key * @throws NoSuchPaddingException Thrown if an invalid padding form is specified * @throws NoSuchAlgorithmException Thrown if an invalid algorithm is specified * @throws InvalidKeyException Thrown id the wrapping key is invalid */ public static byte[] wrapKey( Certificate wrappingCertificate, String wrappingTransformation, Key secretKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalStateException, IllegalBlockSizeException { byte[] wrappedSecretKey; Cipher c; wrappedSecretKey = null; c = null; // Instantiate wrapping cipher c = Cipher.getInstance(wrappingTransformation); // Initialise wrapping cipher c.init(Cipher.WRAP_MODE, wrappingCertificate); // Wrap session key wrappedSecretKey = c.wrap((SecretKey) secretKey); return wrappedSecretKey; }
/** * Wrapping allows to mask/encapsulate/protect the key used Create another key, use a cipher with * it and {@link Cipher#WRAP_MODE} and wrap the original key To unwrap, use a cipher with {@link * Cipher#UNWRAP_MODE} */ static void wrapUnwrapKey() throws Exception { // create a key to wrap KeyGenerator generator = KeyGenerator.getInstance("AES"); generator.init(128); Key keyToBeWrapped = generator.generateKey(); System.out.println("input : " + Utils.toHex(keyToBeWrapped.getEncoded())); // create a wrapper and do the wrapping Cipher cipher = Cipher.getInstance("AESWrap"); KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); keyGenerator.init(128); Key wrapKey = keyGenerator.generateKey(); cipher.init(Cipher.WRAP_MODE, wrapKey); byte[] wrappedKey = cipher.wrap(keyToBeWrapped); System.out.println("wrapped : " + Utils.toHex(wrappedKey)); // unwrap the wrapped key cipher.init(Cipher.UNWRAP_MODE, wrapKey); Key key = cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY); System.out.println("unwrapped: " + Utils.toHex(key.getEncoded())); }
/** * Create a new Profile_ based on a newly generated key pair, with the new private key encrypted * with the password. * * @param name name assigned to this profile object * @param password password that encrypts the private key * @throws Credential.Exception */ public Profile_(String name, char[] password) throws Credential.Exception { // // N.B. Credentials are never deleted, so the delete token created // here will never be used (and thus there's no need to record its // value). // super(CredentialObjectHandler.class, new TitanGuidImpl(), TitanObject.INFINITE_TIME_TO_LIVE); this.name = name; this.limited = false; try { KeyPairGenerator generator = KeyPairGenerator.getInstance(Profile_.KEY_TYPE); generator.initialize(Profile_.KEY_SIZE); KeyPair pair = generator.generateKeyPair(); this.publicKey = pair.getPublic(); Cipher cipher = getCipher(password, Cipher.WRAP_MODE); this.encryptedPrivateKey = cipher.wrap(pair.getPrivate()); } catch (GeneralSecurityException ex) { throw new Credential.Exception(ex); } }
protected final SecuredCEK secureCEK( SecretKey toBeEncrypted, EncryptionMaterials materials, Provider cryptoProvider) { Key kek; if (materials.getKeyPair() != null) { // Do envelope encryption with public key from key pair kek = materials.getKeyPair().getPublic(); } else { // Do envelope encryption with symmetric key kek = materials.getSymmetricKey(); } S3KeyWrapScheme kwScheme = cryptoScheme.getKeyWrapScheme(); String keyWrapAlgo = kwScheme.getKeyWrapAlgorithm(kek); try { if (keyWrapAlgo != null) { Cipher cipher = cryptoProvider == null ? Cipher.getInstance(keyWrapAlgo) : Cipher.getInstance(keyWrapAlgo, cryptoProvider); cipher.init(Cipher.WRAP_MODE, kek, cryptoScheme.getSecureRandom()); return new SecuredCEK(cipher.wrap(toBeEncrypted), keyWrapAlgo); } // fall back to the Encryption Only (EO) key encrypting method Cipher cipher; byte[] toBeEncryptedBytes = toBeEncrypted.getEncoded(); String algo = kek.getAlgorithm(); if (cryptoProvider != null) { cipher = Cipher.getInstance(algo, cryptoProvider); } else { cipher = Cipher.getInstance(algo); // Use default JCE Provider } cipher.init(Cipher.ENCRYPT_MODE, kek); return new SecuredCEK(cipher.doFinal(toBeEncryptedBytes), null); } catch (Exception e) { throw new AmazonClientException("Unable to encrypt symmetric key: " + e.getMessage(), e); } }
private static byte[] createEncryptedPreMaster(boolean fake) { if (fake) { // we do not have to do this calculation to force server to think int len = ((RSAPublicKey) cert.getPublicKey()).getModulus().bitLength() / 8; return new byte[len]; } byte[] preMaster = new byte[48]; preMaster[0] = (byte) 3; preMaster[1] = (byte) 1; SecretKey preMasterKey = new SecretKeySpec(preMaster, "RAW"); Cipher rsa; try { rsa = Cipher.getInstance("RSA/ECB/PKCS1Padding"); rsa.init(Cipher.WRAP_MODE, cert.getPublicKey(), new SecureRandom()); return rsa.wrap(preMasterKey); } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException e) { e.printStackTrace(); throw new RuntimeException("Problem", e); } }
/** * Encrypted a private key or public key with a password and returns the encypted key with the * outputstream * * @param password The password used for encryption * @param output The encrypted key * @param key The public or private key * @throws KOAException This exception will be thrown when there is a getting the key */ private void getKeyEncrypt(String password, OutputStream output, Key key) throws KOAException { try { // create a secret key with the password PBEParameterSpec paramSpec = new PBEParameterSpec(SALT, 20); PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray()); SecretKeyFactory kf = SecretKeyFactory.getInstance(KEY_ENCRIPTION_AKGORITHM); SecretKey passwordKey = kf.generateSecret(keySpec); // encrypt the key Cipher c = Cipher.getInstance(KEY_ENCRIPTION_AKGORITHM); c.init(Cipher.WRAP_MODE, passwordKey, paramSpec); byte[] wrappedKey = c.wrap(key); // write the key to the stream output.write(wrappedKey); } catch (NoSuchAlgorithmException nsae) { KOALogHelper.logError("KOAKeyPair.getKeyEncrypt", "Problem encrypting key", nsae); throw new KOAException(ErrorConstants.SECURITY_KEYPAIR_ENCRYPT, nsae); } catch (NoSuchPaddingException nspe) { KOALogHelper.logError("KOAKeyPair.getKeyEncrypt", "Problem encrypting key", nspe); throw new KOAException(ErrorConstants.SECURITY_KEYPAIR_ENCRYPT, nspe); } catch (IllegalBlockSizeException iape) { KOALogHelper.logError("KOAKeyPair.getKeyEncrypt", "Problem encrypting key", iape); throw new KOAException(ErrorConstants.SECURITY_KEYPAIR_ENCRYPT, iape); } catch (InvalidKeySpecException ikse) { KOALogHelper.logError("KOAKeyPair.getKeyEncrypt", "Problem encrypting key", ikse); throw new KOAException(ErrorConstants.SECURITY_KEYPAIR_ENCRYPT, ikse); } catch (InvalidKeyException ike) { KOALogHelper.logError("KOAKeyPair.getKeyEncrypt", "Problem encrypting key", ike); throw new KOAException(ErrorConstants.SECURITY_KEYPAIR_ENCRYPT, ike); } catch (InvalidAlgorithmParameterException iape) { KOALogHelper.logError("KOAKeyPair.getKeyEncrypt", "Problem encrypting key", iape); throw new KOAException(ErrorConstants.SECURITY_KEYPAIR_ENCRYPT, iape); } catch (IOException ioe) { KOALogHelper.logError("KOAKeyPair.getKeyEncrypt", "Problem encrypting key", ioe); throw new KOAException(ErrorConstants.SECURITY_KEYPAIR_ENCRYPT, ioe); } }
public static void main(String[] args) { try { if (args[0].equals("-genkey")) { KeyPairGenerator pairgen = KeyPairGenerator.getInstance("RSA"); SecureRandom random = new SecureRandom(); pairgen.initialize(KEYSIZE, random); KeyPair keyPair = pairgen.generateKeyPair(); ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(args[1])); out.writeObject(keyPair.getPublic()); out.close(); out = new ObjectOutputStream(new FileOutputStream(args[2])); out.writeObject(keyPair.getPrivate()); out.close(); } else if (args[0].equals("-encrypt")) { KeyGenerator keygen = KeyGenerator.getInstance("AES"); SecureRandom random = new SecureRandom(); keygen.init(random); SecretKey key = keygen.generateKey(); // wrap with RSA public key ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[3])); Key publicKey = (Key) keyIn.readObject(); keyIn.close(); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.WRAP_MODE, publicKey); byte[] wrappedKey = cipher.wrap(key); DataOutputStream out = new DataOutputStream(new FileOutputStream(args[2])); out.writeInt(wrappedKey.length); out.write(wrappedKey); InputStream in = new FileInputStream(args[1]); cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, key); crypt(in, out, cipher); in.close(); out.close(); } else { DataInputStream in = new DataInputStream(new FileInputStream(args[1])); int length = in.readInt(); byte[] wrappedKey = new byte[length]; in.read(wrappedKey, 0, length); // unwrap with RSA private key ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[3])); Key privateKey = (Key) keyIn.readObject(); keyIn.close(); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.UNWRAP_MODE, privateKey); Key key = cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY); OutputStream out = new FileOutputStream(args[2]); cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, key); crypt(in, out, cipher); in.close(); out.close(); } } catch (IOException e) { e.printStackTrace(); } catch (GeneralSecurityException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } }