Пример #1
0
 private void initialize() throws PKCS11Exception {
   if (session == null) {
     session = token.getOpSession();
   }
   PKCS11 p11 = token.p11;
   CK_MECHANISM ckMechanism = new CK_MECHANISM(mechanism);
   switch (mode) {
     case MODE_ENCRYPT:
       p11.C_EncryptInit(session.id(), ckMechanism, p11Key.keyID);
       break;
     case MODE_DECRYPT:
       p11.C_DecryptInit(session.id(), ckMechanism, p11Key.keyID);
       break;
     case MODE_SIGN:
       p11.C_SignInit(session.id(), ckMechanism, p11Key.keyID);
       break;
     case MODE_VERIFY:
       p11.C_VerifyRecoverInit(session.id(), ckMechanism, p11Key.keyID);
       break;
     default:
       throw new AssertionError("internal error");
   }
   bufOfs = 0;
   initialized = true;
 }
Пример #2
0
 // see JCE spec
 protected byte[] engineWrap(Key key) throws InvalidKeyException, IllegalBlockSizeException {
   String keyAlg = key.getAlgorithm();
   P11Key sKey = null;
   try {
     // The conversion may fail, e.g. trying to wrap an AES key on
     // a token that does not support AES, or when the key size is
     // not within the range supported by the token.
     sKey = P11SecretKeyFactory.convertKey(token, key, keyAlg);
   } catch (InvalidKeyException ike) {
     byte[] toBeWrappedKey = key.getEncoded();
     if (toBeWrappedKey == null) {
       throw new InvalidKeyException("wrap() failed, no encoding available", ike);
     }
     // Directly encrypt the key encoding when key conversion failed
     implInit(Cipher.ENCRYPT_MODE, p11Key);
     implUpdate(toBeWrappedKey, 0, toBeWrappedKey.length);
     try {
       return doFinal();
     } catch (BadPaddingException bpe) {
       // should not occur
       throw new InvalidKeyException("wrap() failed", bpe);
     } finally {
       // Restore original mode
       implInit(Cipher.WRAP_MODE, p11Key);
     }
   }
   Session s = null;
   try {
     s = token.getOpSession();
     return token.p11.C_WrapKey(s.id(), new CK_MECHANISM(mechanism), p11Key.keyID, sKey.keyID);
   } catch (PKCS11Exception e) {
     throw new InvalidKeyException("wrap() failed", e);
   } finally {
     token.releaseSession(s);
   }
 }