public static byte[] cryptoPwhash(byte[] passwd, byte[] salt, long opsLimit, NativeLong memLimit, int algorithm) throws SodiumLibraryException { byte[] key = new byte[sodium().crypto_box_seedbytes().intValue()]; logger.info(">>> NavtiveLong size: " + NativeLong.SIZE * 8 + " bits"); int rc = sodium().crypto_pwhash(key, key.length, passwd, passwd.length, salt, opsLimit, memLimit, algorithm); logger.info("crypto_pwhash returned: " + rc); if (rc != 0) { throw new SodiumLibraryException("cryptoPwhash libsodium crypto_pwhash failed, returned " + rc + ", expected 0"); } return key; }
public static byte[] cryptoPwhashScryptSalsa208Sha256(byte[] passwd, byte[] salt, Long opsLimit, NativeLong memLimit) throws SodiumLibraryException { NativeLong salt_length = sodium().crypto_pwhash_scryptsalsa208sha256_saltbytes(); if (salt.length != salt_length.intValue()) { throw new SodiumLibraryException("salt is " + salt.length + ", it must be" + salt_length + " bytes"); } byte[] key = new byte[sodium().crypto_box_seedbytes().intValue()]; int rc = sodium().crypto_pwhash_scryptsalsa208sha256(key, key.length, passwd, passwd.length, salt, opsLimit, memLimit); logger.info("crypto_pwhash_scryptsalsa208sha256 returned: " + rc); if (rc != 0) { throw new SodiumLibraryException("libsodium crypto_pwhash_scryptsalsa208sha256() failed, returned " + rc + ", expected 0"); } return key; }
/** * Encrypts a message with recipient's public key. * * Usage: Alice encrypts a message with Bob's public key and creates authentication tag with her private key * * @param message The message to encrypt * @param nonce {@link SodiumLibrary#cryptoBoxNonceBytes()} bytes of nonce. It must be preserved because it will be needed during decryption * @param publicKey Recipient's public key for encrypting the message * @param privateKey Sender's private key for creating authentication tag * @throws SodiumLibraryException on error * @return encrypted message as an array of bytes */ public static byte[] cryptoBoxEasy(byte[] message, byte[] nonce, byte[] publicKey, byte[] privateKey) throws SodiumLibraryException { NativeLong nonce_len = sodium().crypto_box_noncebytes(); if (nonce.length != nonce_len.intValue()) { throw new SodiumLibraryException("nonce is " + nonce.length + "bytes, it must be" + nonce_len + " bytes"); } byte[] cipherText = new byte[(sodium().crypto_box_macbytes().intValue() + message.length)]; int rc = sodium().crypto_box_easy(cipherText, message,message.length, nonce, publicKey, privateKey); if (rc != 0) { throw new SodiumLibraryException("libsodium crypto_box_easy() failed, returned " + rc + ", expected 0"); } return cipherText; }
/** * Recipient decrypts a message with his private key. * * Usage: Bob (recipient) verifies the message with Alice's (sender) public key and * decrypts the message with his private key. * * @param cipherText Message to decrypt * @param nonce Nonce used during encryption * @param publicKey Sender's (Alice) public key for verifying the message * @param privateKey Recipient's (Bob) Private key to decrypt the message * @throws SodiumLibraryException on error * @return Decrypted message as an array of bytes. */ public static byte[] cryptoBoxOpenEasy(byte[] cipherText, byte[]nonce, byte[] publicKey, byte[] privateKey) throws SodiumLibraryException { NativeLong nonce_len = sodium().crypto_box_noncebytes(); if (nonce.length != nonce_len.intValue()) { throw new SodiumLibraryException("nonce is " + nonce.length + "bytes, it must be" + nonce_len + " bytes"); } byte[] decrypted = new byte[(int) (cipherText.length - sodium().crypto_box_macbytes().intValue())]; int rc = sodium().crypto_box_open_easy(decrypted, cipherText, cipherText.length, nonce, publicKey, privateKey); if (rc != 0) { throw new SodiumLibraryException("libsodium crypto_box_open_easy() failed, returned " + rc + ", expected 0"); } return decrypted; }
/** * 停止实况浏览 * * @param handle 播放句柄 * @return SDKErrorCode 领域层封装的返回码对象 * @see [类、类#方法、类#成员] * @since [eSDK IVS V100R005C30] */ public SDKErrorCode stopRealPlay(long handle) { SDKErrorCode result = new SDKErrorCode(); if (!checkHandle(handle)) { result.setErrCode(1); return result; } int sessionId = CommonService.getSESSIONID(); NativeLong nativaLong = new NativeLong(handle); int resultCode = BaseCablilityJNA.INSTANCE.IVS_SDK_StopRealPlay(sessionId, nativaLong); result.setErrCode(resultCode); return result; }
/** * 停止实况浏览 * * @param handle * 播放句柄 * @return SDKErrorCode 领域层封装的返回码对象 * @see [类、类#方法、类#成员] * @since [eSDK IVS V100R003C00] */ @Override public SDKErrorCode stopRealPlayByIPEx(long handle) { SDKErrorCode result = new SDKErrorCode(); if (!checkHandle(handle)) { result.setErrCode(ErrInfo.IVS_HANDLE_INVALID_ERROR); return result; } int sessionId = super.getIVSSessionId(); NativeLong nativaLong = new NativeLong(handle); int resultCode = super.getBaseCablilityJNA().IVS_SDK_StopRealPlayByIPEx(sessionId, nativaLong); result.setErrCode(resultCode); return result; }
/** * 停止平台录像播放 * * @param handle * 播放句柄 * @return SDKErrorCode 封装领域层的SDKErrorCode对象 * @since eSDK IVS V100R003C00 */ @Override public SDKErrorCode stopPlatformPlayBackByIP(long handle) { SDKErrorCode result = new SDKErrorCode(); if (!checkHandle(handle)) { result.setErrCode(ErrInfo.IVS_HANDLE_INVALID_ERROR); return result; } int sessionId = super.getIVSSessionId(); NativeLong nativaLong = new NativeLong(handle); int resultCode = super.getBaseCablilityJNA().IVS_SDK_StopPlatformPlayBackByIP(sessionId, nativaLong); result.setErrCode(resultCode); return result; }
@Override public SDKErrorCode platformPlayBackPauseByIP(long playHandle) { LOGGER.debug("platformPlayBackPauseByIP method start--->>>"); SDKErrorCode result = new SDKErrorCode(); if (!checkHandle(playHandle)) { result.setErrCode(ErrInfo.IVS_HANDLE_INVALID_ERROR); return result; } NativeLong nativaLong = new NativeLong(playHandle); int sessionId = super.getIVSSessionId(); int resultCode = super.getBaseCablilityJNA().IVS_SDK_PlatformPlayBackPauseByIP(sessionId, nativaLong); result.setErrCode(resultCode); LOGGER.debug("platformPlayBackPauseByIP method result code:" + resultCode); LOGGER.debug("platformPlayBackPauseByIP method end--->>>"); return result; }
@Override public SDKErrorCode platformPlayBackResumeByIP(long playHandle) { LOGGER.debug("platformPlayBackResumeByIP method start--->>>"); SDKErrorCode result = new SDKErrorCode(); if (!checkHandle(playHandle)) { result.setErrCode(ErrInfo.IVS_HANDLE_INVALID_ERROR); return result; } NativeLong nativaLong = new NativeLong(playHandle); int sessionId = super.getIVSSessionId(); int resultCode = super.getBaseCablilityJNA().IVS_SDK_PlatformPlayBackResumeByIP(sessionId, nativaLong); result.setErrCode(resultCode); LOGGER.debug("platformPlayBackResumeByIP method result code:" + resultCode); LOGGER.debug("platformPlayBackResumeByIP method end--->>>"); return result; }
/** * 设置平台录像码流回放时间 * * @param playHandle * 播放句柄 * @param time * 回放时间 * @return SDKErrorCode 领域层封装的返回码对象 * @see * @since eSDK IVS V100R003C30SPC100 */ @Override public SDKErrorCode setPlayBackTimeByIP(long playHandle, int time) { LOGGER.debug("setPlayBackTimeByIP method start--->>>"); SDKErrorCode result = new SDKErrorCode(); if (!checkHandle(playHandle)) { result.setErrCode(ErrInfo.IVS_HANDLE_INVALID_ERROR); return result; } NativeLong nativaLong = new NativeLong(playHandle); int sessionId = super.getIVSSessionId(); int resultCode = super.getBaseCablilityJNA().IVS_SDK_SetPlayBackTimeByIP(sessionId, nativaLong, time); result.setErrCode(resultCode); LOGGER.debug("setPlayBackTimeByIP method result code:" + resultCode); LOGGER.debug("setPlayBackTimeByIP method end--->>>"); return result; }
/** * 设置平台录像码流回放速度 * * @param playHandle * 播放句柄 * @param speed * 播放速度 * @return SDKErrorCode 领域层封装的返回码对象 * @see * @since eSDK IVS V100R003C30SPC100 */ @Override public SDKErrorCode setPlayBackSpeedByIP(long playHandle, float speed) { LOGGER.debug("setPlayBackSpeedByIP method start--->>>"); SDKErrorCode result = new SDKErrorCode(); if (!checkHandle(playHandle)) { result.setErrCode(ErrInfo.IVS_HANDLE_INVALID_ERROR); return result; } NativeLong nativaLong = new NativeLong(playHandle); int sessionId = super.getIVSSessionId(); int resultCode = super.getBaseCablilityJNA().IVS_SDK_SetPlayBackSpeedByIP(sessionId, nativaLong, speed); result.setErrCode(resultCode); LOGGER.debug("setPlayBackSpeedByIP method result code:" + resultCode); LOGGER.debug("setPlayBackSpeedByIP method end--->>>"); return result; }
Token(NativeLong slotId) throws Pkcs11CallerException { RtPkcs11 pkcs11 = RtPkcs11Library.getInstance(); synchronized (pkcs11) { mId = slotId; initTokenInfo(); NativeLongByReference session = new NativeLongByReference(); NativeLong rv = RtPkcs11Library.getInstance().C_OpenSession(mId, Pkcs11Constants.CKF_SERIAL_SESSION, null, null, session); if (!rv.equals(Pkcs11Constants.CKR_OK)) throw Pkcs11Exception.exceptionWithCode(rv); mSession = session.getValue(); try { initCertificatesList(pkcs11); } catch (Pkcs11CallerException exception) { try { close(); } catch (Pkcs11CallerException exception2) { } throw exception; } } }
protected void slotEventHappened(NativeLong id) throws Pkcs11Exception { CK_SLOT_INFO slotInfo = new CK_SLOT_INFO(); NativeLong rv; rv = RtPkcs11Library.getInstance().C_GetSlotInfo(id, slotInfo); if (!rv.equals(Pkcs11Constants.CKR_OK)) { throw Pkcs11Exception.exceptionWithCode(rv); } EventType event; if ((Pkcs11Constants.CKF_TOKEN_PRESENT.intValue() & slotInfo.flags.intValue()) != 0x00) { event = EventType.SD; } else { event = EventType.SR; } if (lastSlotEvent.get(id) == event) { mHandler.post(new EventRunnable(oppositeEvent(event), id)); lastSlotEvent.put(id, oppositeEvent(event)); } mHandler.post(new EventRunnable(event, id)); lastSlotEvent.put(id, event); }
AcceptableState processCurrentStateR1W0TIF(EventType event, NativeLong slotId, Token token) throws TokenManagerException { AcceptableState newState; switch (event) { case SD: newState = AcceptableState.R0W1SD; sendTWBA(slotId); startTilThread(slotId); break; case SR: newState = AcceptableState.R1W0SR; break; case TIL: case TIF: throw new TokenManagerException("Input not accepted by state"); default: throw new TokenManagerException("Unexpected unfiltered incoming event"); } return newState; }
public NativeLong getPrivateKeyHandle(RtPkcs11 pkcs11, NativeLong session) throws Pkcs11CallerException { CK_ATTRIBUTE[] template = (CK_ATTRIBUTE[]) (new CK_ATTRIBUTE()).toArray(2); final NativeLongByReference keyClass = new NativeLongByReference(Pkcs11Constants.CKO_PRIVATE_KEY); template[0].type = Pkcs11Constants.CKA_CLASS; template[0].pValue = keyClass.getPointer(); template[0].ulValueLen = new NativeLong(NativeLong.SIZE); ByteBuffer idBuffer = ByteBuffer.allocateDirect(mKeyPairId.length); idBuffer.put(mKeyPairId); template[1].type = Pkcs11Constants.CKA_ID; template[1].pValue = Native.getDirectBufferPointer(idBuffer); template[1].ulValueLen = new NativeLong(mKeyPairId.length); return findObject(pkcs11, session, template); }
@Override public GetProgramInfoResult GetProgramInfo(long dabIndex) { byte b = 0; byte ServiceComponentID = new Byte(b); byte ServiceID = new Byte(b); byte EnsembleID = new Byte(b); if (!monkeyBoard.GetProgramInfo(new NativeLong(dabIndex), ServiceComponentID, ServiceID, EnsembleID)) return null; GetProgramInfoResult r = new GetProgramInfoResult(); r.setServiceComponentID(ServiceComponentID); r.setEnsembleID(EnsembleID); r.setServiceID(ServiceID); return r; }
AcceptableState processCurrentStateR1W0SR(EventType event, NativeLong slotId, Token token) throws TokenManagerException { AcceptableState newState; switch (event) { case SD: newState = AcceptableState.R0W1SD; sendTWBA(slotId); startTilThread(slotId); break; case SR: case TIL: case TIF: throw new TokenManagerException("Input not accepted by state"); default: throw new TokenManagerException("Unexpected unfiltered incoming event"); } return newState; }
public synchronized void init(Context context) { if (mContext != null) return; mContext = context; Resources res = mContext.getResources(); if (res == null) { return; } int intRV[] = res.getIntArray(R.array.rv); String messages[] = res.getStringArray(R.array.rvMessages); assert (intRV.length == messages.length); for (int i = 0; i < intRV.length; ++i) { mErrorMessages.put(new NativeLong(intRV[i]), messages[i]); } mGenericMessage = res.getString(R.string.generic_error); }
private Pointer[] createFSEventStream() throws IOException { final Pointer root = cf.CFStringCreateWithCString(Pointer.NULL,"/",ENC_MAC_ROMAN); //NOI18N if (root == Pointer.NULL) { throw new IOException("Path creation failed."); //NOI18N } final Pointer arr = cf.CFArrayCreateMutable(Pointer.NULL, new NativeLong(1), Pointer.NULL); if (arr == Pointer.NULL) { throw new IOException("Path list creation failed."); //NOI18N } cf.CFArrayAppendValue(arr, root); final Pointer eventStream = cs.FSEventStreamCreate(Pointer.NULL, callback, Pointer.NULL, arr, kFSEventStreamEventIdSinceNow, LATENCY, kFSEventStreamCreateFlagNoDefer); if (eventStream == Pointer.NULL) { throw new IOException("Creation of FSEventStream failed."); //NOI18N } final Pointer loop = cf.CFRunLoopGetCurrent(); if (eventStream == Pointer.NULL) { throw new IOException("Cannot find run loop for caller."); //NOI18N } final Pointer kCFRunLoopDefaultMode = findDefaultMode(loop); if (kCFRunLoopDefaultMode == null) { throw new IOException("Caller has no defaul run loop mode."); //NOI18N } cs.FSEventStreamScheduleWithRunLoop(eventStream, loop, kCFRunLoopDefaultMode); if (LOG.isLoggable(DEBUG_LOG_LEVEL)) { LOG.log(DEBUG_LOG_LEVEL, getStreamDescription(eventStream)); } cs.FSEventStreamStart(eventStream); return new Pointer[] {eventStream, loop}; }
private Pointer findDefaultMode(final Pointer runLoop) { final Pointer modes = cf.CFRunLoopCopyAllModes(runLoop); if (modes != Pointer.NULL) { final int modesCount = cf.CFArrayGetCount(modes).intValue(); for (int i=0; i< modesCount; i++) { final Pointer mode = cf.CFArrayGetValueAtIndex(modes, new NativeLong(i)); if (mode != Pointer.NULL && DEFAULT_RUN_LOOP_MODE.equals(cf.CFStringGetCStringPtr(mode, ENC_MAC_ROMAN))) { return mode; } } } return null; }
@Override public void invoke(Pointer streamRef, Pointer clientCallBackInfo, NativeLong numEvents, Pointer eventPaths, Pointer eventFlags, Pointer eventIds) { final long st = System.currentTimeMillis(); final int length = numEvents.intValue(); final Pointer[] pointers = eventPaths.getPointerArray(0, length); int flags[]; if (eventFlags == null) { flags = new int[length]; LOG.log(DEBUG_LOG_LEVEL, "FSEventStreamCallback eventFlags == null, expected int[] of size {0}", length); //NOI18N } else { flags = eventFlags.getIntArray(0, length); } for (int i=0; i<length; i++) { final Pointer p = pointers[i]; int flag = flags[i]; final String path = p.getString(0); if ((flag & kFSEventStreamEventFlagMustScanSubDirs) == kFSEventStreamEventFlagMustScanSubDirs || (flag & kFSEventStreamEventFlagMount) == kFSEventStreamEventFlagMount || (flag & kFSEventStreamEventFlagUnmount) == kFSEventStreamEventFlagUnmount) { events.add(ALL_CHANGE); } else { events.add(path); } LOG.log(DEBUG_LOG_LEVEL, "Event on {0}", new Object[]{path}); } LOG.log(PERF_LOG_LEVEL, "Callback time: {0}", (System.currentTimeMillis() - st)); }
/** * It's a heavy init method. */ public void init() { for (int i = 0; i < poolSize; i++) { ByteBuffer byteBuffer = ByteBuffer.allocateDirect(fileSize); final long address = ((DirectBuffer) byteBuffer).address(); Pointer pointer = new Pointer(address); LibC.INSTANCE.mlock(pointer, new NativeLong(fileSize)); availableBuffers.offer(byteBuffer); } }
public void destroy() { for (ByteBuffer byteBuffer : availableBuffers) { final long address = ((DirectBuffer) byteBuffer).address(); Pointer pointer = new Pointer(address); LibC.INSTANCE.munlock(pointer, new NativeLong(fileSize)); } }
public void munlock() { final long beginTime = System.currentTimeMillis(); final long address = ((DirectBuffer) (this.mappedByteBuffer)).address(); Pointer pointer = new Pointer(address); int ret = LibC.INSTANCE.munlock(pointer, new NativeLong(this.fileSize)); log.info("munlock {} {} {} ret = {} time consuming = {}", address, this.fileName, this.fileSize, ret, System.currentTimeMillis() - beginTime); }
public void munlock() { final long beginTime = System.currentTimeMillis(); final long address = ((DirectBuffer) (this.mappedByteBuffer)).address(); Pointer pointer = new Pointer(address); int ret = PlatformLibC.munlock(pointer, new NativeLong(this.fileSize)); log.info("munlock {} {} {} ret = {} time consuming = {}", new Object[]{ address, this.fileName, this.fileSize, ret, System.currentTimeMillis() - beginTime }); }
public static int mlock(Pointer address, NativeLong size) { if (isWindows) { return cLibrary.VirtualLock(address, size); } else { return cLibrary.mlock(address, size); } }
public static int munlock(Pointer address, NativeLong size) { if (isWindows) { return cLibrary.VirtualUnlock(address, size); } else { return cLibrary.munlock(address, size); } }
public static int madvise(Pointer address, NativeLong size, int advice) { if (isWindows) { return 0; // no implementation in Windows 7 and earlier } else { return cLibrary.madvise(address, size, advice); } }
/** * It's a heavy init method. * * 这里使用 堆外内存 池化的组合方式,来对生命周期较短,但涉及到I/O操作的对象 * 进行堆外内存的在使用(Netty中就使用了该方式) * * */ public void init() { for (int i = 0; i < poolSize; i++) { ByteBuffer byteBuffer = ByteBuffer.allocateDirect(fileSize); final long address = ((DirectBuffer) byteBuffer).address(); Pointer pointer = new Pointer(address); //过mlock可以将进程使用的部分或者全部的地址空间锁定在物理内存中,防止其被交换到swap空间。 //对时间敏感的应用会希望全部使用物理内存,提高数据访问和操作的效率。 LibC.INSTANCE.mlock(pointer, new NativeLong(fileSize)); availableBuffers.offer(byteBuffer); } }
/** * readProcessMemory to memory. */ long readProcessMemory(Pointer baseAddress, Memory goal) { NativeLong sizeAvalaible = new NativeLong(goal.size()); NativeLongByReference bytesReadRefernce = new NativeLongByReference(); boolean ret = MyKernel32.INSTANCE.ReadProcessMemory( _processInformation.hProcess.getPointer(), baseAddress, goal, sizeAvalaible, bytesReadRefernce); if (!ret) log("pid " + _pid + " ReadProcessMemory returns " + ret); long bytesRead = bytesReadRefernce.getValue().longValue(); return bytesRead; }
public ReplFileStatsStruct(NativeLong TotalFiles, NativeLong FilesCompleted, NativeLong NotesAdded, NativeLong NotesDeleted, NativeLong NotesUpdated, NativeLong Successful, NativeLong Failed, NativeLong NumberErrors) { super(); this.TotalFiles = TotalFiles; this.FilesCompleted = FilesCompleted; this.NotesAdded = NotesAdded; this.NotesDeleted = NotesDeleted; this.NotesUpdated = NotesUpdated; this.Successful = Successful; this.Failed = Failed; this.NumberErrors = NumberErrors; }
public static ReplFileStatsStruct newInstance(final NativeLong TotalFiles, final NativeLong FilesCompleted, final NativeLong NotesAdded, final NativeLong NotesDeleted, final NativeLong NotesUpdated, final NativeLong Successful, final NativeLong Failed, final NativeLong NumberErrors) { return AccessController.doPrivileged(new PrivilegedAction<ReplFileStatsStruct>() { @Override public ReplFileStatsStruct run() { return new ReplFileStatsStruct(TotalFiles, FilesCompleted, NotesAdded, NotesDeleted, NotesUpdated, Successful, Failed, NumberErrors); } }); }
public static ReplServStatsStruct newInstance(final ReplFileStatsStruct Pull, final ReplFileStatsStruct Push, final NativeLong StubsInitialized, final NativeLong TotalUnreadExchanges, final NativeLong NumberErrors, final short LastError) { return AccessController.doPrivileged(new PrivilegedAction<ReplServStatsStruct>() { @Override public ReplServStatsStruct run() { return new ReplServStatsStruct(Pull, Push, StubsInitialized, TotalUnreadExchanges, NumberErrors, LastError); } }); }
@Override public void setNativeLong(long offset, NativeLong value) { if (m_sealed) throw new UnsupportedOperationException(); super.setNativeLong(offset, value); }
private boolean checkHandle(long playHandle) { if (4 == NativeLong.SIZE) { if (4294967295L < playHandle || -2147483648L > playHandle) { return false; } } return true; }
private boolean checkHandle(long playHandle) { if (IVSConstant.IVS_OS_32 == NativeLong.SIZE) { if (IVSConstant.IVS_INT_MAX < playHandle || IVSConstant.IVS_INT_MIN > playHandle) { return false; } } return true; }
/** * @param retVal the result value of error. */ private void throwOnError(int retVal) { if (retVal != 1) { NativeLong err = OpenSslNativeJna.ERR_peek_error(); String errdesc = OpenSslNativeJna.ERR_error_string(err, null); if (context != null) { OpenSslNativeJna.EVP_CIPHER_CTX_cleanup(context); } throw new RuntimeException("return code "+retVal+" from OpenSSL. Err code is "+err+": "+errdesc); } }
/** * @param retVal the result value of error. */ private void throwOnError(int retVal) { if (retVal != 1) { NativeLong err = OpenSslNativeJna.ERR_peek_error(); String errdesc = OpenSslNativeJna.ERR_error_string(err, null); close(); throw new RuntimeException("return code " + retVal + " from OpenSSL. Err code is " + err + ": " + errdesc); } }