Net.Pkcs11Interop.HighLevelAPI81.Session.WrapKey C# (CSharp) Method

WrapKey() public method

Wraps (i.e., encrypts) a private or secret key
public WrapKey ( Mechanism mechanism, ObjectHandle wrappingKeyHandle, ObjectHandle keyHandle ) : byte[]
mechanism Mechanism Wrapping mechanism
wrappingKeyHandle ObjectHandle Handle of wrapping key
keyHandle ObjectHandle Handle of key to be wrapped
return byte[]
        public byte[] WrapKey(Mechanism mechanism, ObjectHandle wrappingKeyHandle, ObjectHandle keyHandle)
        {
            if (this._disposed)
                throw new ObjectDisposedException(this.GetType().FullName);

            if (mechanism == null)
                throw new ArgumentNullException("mechanism");
            
            if (wrappingKeyHandle == null)
                throw new ArgumentNullException("wrappingKeyHandle");
            
            if (keyHandle == null)
                throw new ArgumentNullException("keyHandle");

            CK_MECHANISM ckMechanism = mechanism.CkMechanism;

            ulong wrappedKeyLen = 0;
            CKR rv = _p11.C_WrapKey(_sessionId, ref ckMechanism, wrappingKeyHandle.ObjectId, keyHandle.ObjectId, null, ref wrappedKeyLen);
            if (rv != CKR.CKR_OK)
                throw new Pkcs11Exception("C_WrapKey", rv);

            byte[] wrappedKey = new byte[wrappedKeyLen];
            rv = _p11.C_WrapKey(_sessionId, ref ckMechanism, wrappingKeyHandle.ObjectId, keyHandle.ObjectId, wrappedKey, ref wrappedKeyLen);
            if (rv != CKR.CKR_OK)
                throw new Pkcs11Exception("C_WrapKey", rv);

            if (wrappedKey.Length != Convert.ToInt32(wrappedKeyLen))
                Array.Resize(ref wrappedKey, Convert.ToInt32(wrappedKeyLen));

            return wrappedKey;
        }