Java Code Examples for com.sun.jna.Memory#write()

The following examples show how to use com.sun.jna.Memory#write() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WindowsCryptUtils.java    From consulo with Apache License 2.0 6 votes vote down vote up
/**
 * Protect the specified byte range
 *
 * @param data the data to protect
 * @return the the protected form the data
 */
public static byte[] protect(byte[] data) throws MasterPasswordUnavailableException {
  if(data.length == 0) {
    return data;
  }
  Memory input = new Memory(data.length);
  input.write(0, data, 0, data.length);
  Crypt32.DATA_BLOB in = new Crypt32.DATA_BLOB();
  in.cbData = new W32API.DWORD(data.length);
  in.pbData = input;
  Crypt32.DATA_BLOB out = new Crypt32.DATA_BLOB();
  out.pbData = Pointer.NULL;
  Crypt32 crypt = Crypt32.INSTANCE;
  Kernel32 kernel = Kernel32.INSTANCE;
  boolean rc = crypt.CryptProtectData(in, "Master Key", Pointer.NULL, Pointer.NULL, Pointer.NULL, new W32API.DWORD(0), out);
  if (!rc) {
    W32API.DWORD drc = kernel.GetLastError();
    throw new MasterPasswordUnavailableException("CryptProtectData failed: " + drc.intValue());
  }
  else {
    byte[] output = new byte[out.cbData.intValue()];
    out.pbData.read(0, output, 0, output.length);
    kernel.LocalFree(out.pbData);
    return output;
  }
}
 
Example 2
Source File: WindowsCryptUtils.java    From consulo with Apache License 2.0 6 votes vote down vote up
/**
 * Unprotect the specified byte range
 *
 * @param data the data to protect
 * @return the the protected form the data
 */
public static byte[] unprotect(byte[] data) throws MasterPasswordUnavailableException {
  if(data.length == 0) {
    return data;
  }
  Memory input = new Memory(data.length);
  input.write(0, data, 0, data.length);
  Crypt32.DATA_BLOB in = new Crypt32.DATA_BLOB();
  in.cbData = new W32API.DWORD(data.length);
  in.pbData = input;
  Crypt32.DATA_BLOB out = new Crypt32.DATA_BLOB();
  out.pbData = Pointer.NULL;
  Crypt32 crypt = Crypt32.INSTANCE;
  Kernel32 kernel = Kernel32.INSTANCE;
  boolean rc = crypt.CryptUnprotectData(in, Pointer.NULL, Pointer.NULL, Pointer.NULL, Pointer.NULL, new W32API.DWORD(0), out);
  if (!rc) {
    W32API.DWORD drc = kernel.GetLastError();
    throw new MasterPasswordUnavailableException("CryptProtectData failed: " + drc.intValue());
  }
  else {
    byte[] output = new byte[out.cbData.intValue()];
    out.pbData.read(0, output, 0, output.length);
    kernel.LocalFree(out.pbData);
    return output;
  }
}
 
Example 3
Source File: SecureStorageWindowsManager.java    From snowflake-jdbc with Apache License 2.0 5 votes vote down vote up
public SecureStorageStatus setCredential(String host, String user, String token)
{
  if (Strings.isNullOrEmpty(token))
  {
    logger.info("No token provided");
    return SecureStorageStatus.SUCCESS;
  }

  byte[] credBlob = token.getBytes(StandardCharsets.UTF_16LE);
  Memory credBlobMem = new Memory(credBlob.length);
  credBlobMem.write(0, credBlob, 0, credBlob.length);

  String target = SecureStorageManager.convertTarget(host, user);

  SecureStorageWindowsCredential cred = new SecureStorageWindowsCredential();
  cred.Type = SecureStorageWindowsCredentialType.CRED_TYPE_GENERIC.getType();
  cred.TargetName = new WString(target);
  cred.CredentialBlobSize = (int) credBlobMem.size();
  cred.CredentialBlob = credBlobMem;
  cred.Persist = SecureStorageWindowsCredentialPersistType.CRED_PERSIST_LOCAL_MACHINE.getType();
  cred.UserName = new WString(user.toUpperCase());

  boolean ret = false;
  synchronized (advapi32Lib)
  {
    ret = advapi32Lib.CredWriteW(cred, 0);
  }

  if (!ret)
  {
    logger.info(String.format("Failed to write to Windows Credential Manager. Error code = %d", Native.getLastError()));
    return SecureStorageStatus.FAILURE;
  }
  logger.info("Wrote to Windows Credential Manager successfully");

  return SecureStorageStatus.SUCCESS;
}
 
Example 4
Source File: JnaEventHandle.java    From jaybird with GNU Lesser General Public License v2.1 5 votes vote down vote up
JnaEventHandle(String eventName, EventHandler eventHandler, Encoding encoding) {
    super(eventName, eventHandler);
    // Requires null-termination
    final byte[] eventNameBytes = encoding.encodeToCharset(eventName + '\0');
    if (eventNameBytes.length > 256) {
        throw new IllegalArgumentException("Event name as bytes too long");
    }
    eventNameMemory = new Memory(eventNameBytes.length);
    eventNameMemory.write(0, eventNameBytes, 0, eventNameBytes.length);
}
 
Example 5
Source File: Win32Protect.java    From netbeans with Apache License 2.0 4 votes vote down vote up
void store(byte[] data) {
    cbData = data.length;
    pbData = new Memory(data.length);
    pbData.write(0, data, 0, cbData);
}
 
Example 6
Source File: IDUtils.java    From domino-jna with Apache License 2.0 4 votes vote down vote up
/**
 * Internal helper method to fetch the ID from the ID vault.
 * 
 * @param userName Name of user whose ID is being put into vault - either abbreviated or canonical format
 * @param password Password to id file being uploaded to the vault
 * @param idPath if not null, path to where the download ID file should be created or overwritten
 * @param rethKFC64 if not null, returns the hKFC handle to the in-memory id for 64 bit
 * @param rethKFC32 if not null, returns the hKFC handle to the in-memory id for 32 bit
 * @param serverName Name of server to contact
 * @return the vault server name
 * @throws NotesError in case of problems, e.g. ERR 22792 Wrong Password
 */
private static String _getUserIdFromVault(String userName, String password, String idPath, LongByReference rethKFC64, IntByReference rethKFC32, String serverName) {
	String userNameCanonical = NotesNamingUtils.toCanonicalName(userName);
	Memory userNameCanonicalMem = NotesStringUtils.toLMBCS(userNameCanonical, true);
	Memory passwordMem = NotesStringUtils.toLMBCS(password, true);
	Memory idPathMem = NotesStringUtils.toLMBCS(idPath, true);
	Memory serverNameMem = new Memory(NotesConstants.MAXPATH);
	{
		Memory serverNameParamMem = NotesStringUtils.toLMBCS(serverName, true);
		if (serverNameParamMem!=null && (serverNameParamMem.size() > NotesConstants.MAXPATH)) {
			throw new IllegalArgumentException("Servername length cannot exceed MAXPATH ("+NotesConstants.MAXPATH+" characters)");
		}
		if (serverNameParamMem!=null) {
			byte[] serverNameParamArr = serverNameParamMem.getByteArray(0, (int) serverNameParamMem.size());
			serverNameMem.write(0, serverNameParamArr, 0, serverNameParamArr.length);
		}
		else {
			serverNameMem.setByte(0, (byte) 0);
		}
	}
	
	short result;
	if (PlatformUtils.is64Bit()) {
		result = NotesNativeAPI64.get().SECidfGet(userNameCanonicalMem, passwordMem, idPathMem, rethKFC64, serverNameMem, 0, (short) 0, null);
	}
	else {
		result = NotesNativeAPI32.get().SECidfGet(userNameCanonicalMem, passwordMem, idPathMem, rethKFC32, serverNameMem, 0, (short) 0, null);
	}
	NotesErrorUtils.checkResult(result);
	
	int vaultServerNameLength = 0;
	for (int i=0; i<serverNameMem.size(); i++) {
		vaultServerNameLength = i;
		if (serverNameMem.getByte(i) == 0) {
			break;
		}
	}
	
	String vaultServerName = NotesStringUtils.fromLMBCS(serverNameMem, vaultServerNameLength);
	return vaultServerName;
}
 
Example 7
Source File: IDUtils.java    From domino-jna with Apache License 2.0 4 votes vote down vote up
/**
 * Will open the ID file name provided, locate a vault server for user <code>userName</code>,
 * upload the ID file contents to the vault, then return with the vault server name.<br>
 * 
 * @param userName Name of user whose ID is being put into vault - either abbreviated or canonical format
 * @param password Password to id file being uploaded to the vault
 * @param idPath Path to where the download ID file should be created or overwritten or null to use the in-memory id
 * @param phKFC64 handle to the in-memory id or null to use an id file on disk for 64 bit
 * @param phKFC32 handle to the in-memory id or null to use an id file on disk for 32 bit
 * @param serverName Name of server to contact
 * @return the vault server name
 * @throws NotesError in case of problems, e.g. ERR 22792 Wrong Password
 */
private static String _putUserIdIntoVault(String userName, String password, String idPath,
		LongByReference phKFC64, IntByReference phKFC32, String serverName) {
	//opening any database on the server is required before putting the id fault, according to the
	//C API documentation and sample "idvault.c"
	NotesDatabase anyServerDb = new NotesDatabase(serverName, "names.nsf", (String) null);
	try {
		String userNameCanonical = NotesNamingUtils.toCanonicalName(userName);
		Memory userNameCanonicalMem = NotesStringUtils.toLMBCS(userNameCanonical, true);
		Memory passwordMem = NotesStringUtils.toLMBCS(password, true);
		Memory idPathMem = NotesStringUtils.toLMBCS(idPath, true);
		Memory serverNameMem = new Memory(NotesConstants.MAXPATH);
		{
			Memory serverNameParamMem = NotesStringUtils.toLMBCS(serverName, true);
			if (serverNameParamMem!=null && (serverNameParamMem.size() > NotesConstants.MAXPATH)) {
				throw new IllegalArgumentException("Servername length cannot exceed MAXPATH ("+NotesConstants.MAXPATH+" characters)");
			}
			if (serverNameParamMem!=null) {
				byte[] serverNameParamArr = serverNameParamMem.getByteArray(0, (int) serverNameParamMem.size());
				serverNameMem.write(0, serverNameParamArr, 0, serverNameParamArr.length);
			}
			else {
				serverNameMem.setByte(0, (byte) 0);
			}
		}
		
		short result;
		if (PlatformUtils.is64Bit()) {
			result = NotesNativeAPI64.get().SECKFMOpen (phKFC64, idPathMem, passwordMem, NotesConstants.SECKFM_open_All, 0, null);
		}
		else {
			result = NotesNativeAPI32.get().SECKFMOpen (phKFC32, idPathMem, passwordMem, NotesConstants.SECKFM_open_All, 0, null);
		}
		NotesErrorUtils.checkResult(result);
		
		try {
			if (PlatformUtils.is64Bit()) {
				result = NotesNativeAPI64.get().SECidfPut(userNameCanonicalMem, passwordMem, idPathMem, phKFC64, serverNameMem, 0, (short) 0, null);
			}
			else {
				result = NotesNativeAPI32.get().SECidfPut(userNameCanonicalMem, passwordMem, idPathMem, phKFC32, serverNameMem, 0, (short) 0, null);
			}
			NotesErrorUtils.checkResult(result);
		}
		finally {
			if (PlatformUtils.is64Bit()) {
				result = NotesNativeAPI64.get().SECKFMClose(phKFC64, NotesConstants.SECKFM_close_WriteIdFile, 0, null);
				
			}
			else {
				result = NotesNativeAPI32.get().SECKFMClose(phKFC32, NotesConstants.SECKFM_close_WriteIdFile, 0, null);
			}
			NotesErrorUtils.checkResult(result);
		}
				
		int vaultServerNameLength = 0;
		for (int i=0; i<serverNameMem.size(); i++) {
			if (serverNameMem.getByte(i) == 0) {
				break;
			}
			else {
				vaultServerNameLength = i;
			}
		}
		
		String vaultServerName = NotesStringUtils.fromLMBCS(serverNameMem, vaultServerNameLength);
		return vaultServerName;

	}
	finally {
		anyServerDb.recycle();
	}
}
 
Example 8
Source File: IDUtils.java    From domino-jna with Apache License 2.0 4 votes vote down vote up
/**
 * Will open the ID file name provided, locate a vault server, synch the ID file contents to the vault,
 * then return the synched content. If successful the vault server name is returned.

 * @param userName Name of user whose ID is being put into vault - either abbreviated or canonical format
 * @param password Password to id file being uploaded to the vault
 * @param idPath Path to where the download ID file should be created or overwritten
 * @param serverName Name of server to contact
 * @return sync result
 */
public static SyncResult syncUserIdWithVault(String userName, String password, String idPath, String serverName) {
	String userNameCanonical = NotesNamingUtils.toCanonicalName(userName);
	Memory userNameCanonicalMem = NotesStringUtils.toLMBCS(userNameCanonical, true);
	Memory passwordMem = NotesStringUtils.toLMBCS(password, true);
	Memory idPathMem = NotesStringUtils.toLMBCS(idPath, true);
	Memory serverNameMem = new Memory(NotesConstants.MAXPATH);
	{
		Memory serverNameParamMem = NotesStringUtils.toLMBCS(serverName, true);
		if (serverNameParamMem!=null && (serverNameParamMem.size() > NotesConstants.MAXPATH)) {
			throw new IllegalArgumentException("Servername length cannot exceed MAXPATH ("+NotesConstants.MAXPATH+" characters)");
		}
		if (serverNameParamMem!=null) {
			byte[] serverNameParamArr = serverNameParamMem.getByteArray(0, (int) serverNameParamMem.size());
			serverNameMem.write(0, serverNameParamArr, 0, serverNameParamArr.length);
		}
		else {
			serverNameMem.setByte(0, (byte) 0);
		}
	}
	
	LongByReference phKFC64 = new LongByReference();
	IntByReference phKFC32 = new IntByReference();
	IntByReference retdwFlags = new IntByReference();
	
	short result;
	if (PlatformUtils.is64Bit()) {
		result = NotesNativeAPI64.get().SECKFMOpen (phKFC64, idPathMem, passwordMem, NotesConstants.SECKFM_open_All, 0, null);
	}
	else {
		result = NotesNativeAPI32.get().SECKFMOpen (phKFC32, idPathMem, passwordMem, NotesConstants.SECKFM_open_All, 0, null);
	}
	NotesErrorUtils.checkResult(result);
	
	try {
		if (PlatformUtils.is64Bit()) {
			result = NotesNativeAPI64.get().SECidfSync(userNameCanonicalMem, passwordMem, idPathMem, phKFC64, serverNameMem, 0, (short) 0, null, retdwFlags);
		}
		else {
			result = NotesNativeAPI32.get().SECidfSync(userNameCanonicalMem, passwordMem, idPathMem, phKFC32, serverNameMem, 0, (short) 0, null, retdwFlags);
		}
		NotesErrorUtils.checkResult(result);
	}
	finally {
		if (PlatformUtils.is64Bit()) {
			result = NotesNativeAPI64.get().SECKFMClose(phKFC64, NotesConstants.SECKFM_close_WriteIdFile, 0, null);
		}
		else {
			result = NotesNativeAPI32.get().SECKFMClose(phKFC32, NotesConstants.SECKFM_close_WriteIdFile, 0, null);
		}
		NotesErrorUtils.checkResult(result);
	}

	NotesErrorUtils.checkResult(result);
	
	int vaultServerNameLength = 0;
	for (int i=0; i<serverNameMem.size(); i++) {
		vaultServerNameLength = i;
		if (serverNameMem.getByte(i) == 0) {
			break;
		}
	}
	
	String vaultServerName = NotesStringUtils.fromLMBCS(serverNameMem, vaultServerNameLength);
	
	SyncResult syncResult = new SyncResult(vaultServerName, retdwFlags.getValue());
	return syncResult;
}
 
Example 9
Source File: SecureStorageManagerTest.java    From snowflake-jdbc with Apache License 2.0 4 votes vote down vote up
static MockMacKeychainItem buildMacKeychainItem(int itemLength, byte[] itemData)
{
  Memory itemMem = new Memory(itemLength);
  itemMem.write(0, itemData, 0, itemLength);
  return new MockMacKeychainItem(itemLength, itemMem);
}
 
Example 10
Source File: Advapi32Util.java    From jpexs-decompiler with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Get a table of registry values.
 *
 * @param hKey Registry key.
 * @return Table of values.
 */
public static TreeMap<String, Object> registryGetValues(HKEY hKey) {
    IntByReference lpcValues = new IntByReference();
    IntByReference lpcMaxValueNameLen = new IntByReference();
    IntByReference lpcMaxValueLen = new IntByReference();
    int rc = Advapi32.INSTANCE.RegQueryInfoKey(hKey, null, null, null, null,
            null, null, lpcValues, lpcMaxValueNameLen, lpcMaxValueLen, null, null);
    if (rc != W32Errors.ERROR_SUCCESS) {
        throw new Win32Exception(rc);
    }
    TreeMap<String, Object> keyValues = new TreeMap<>();
    char[] name = new char[lpcMaxValueNameLen.getValue() + 1];
    byte[] data = new byte[lpcMaxValueLen.getValue()];
    for (int i = 0; i < lpcValues.getValue(); i++) {
        IntByReference lpcchValueName = new IntByReference(lpcMaxValueNameLen.getValue() + 1);
        IntByReference lpcbData = new IntByReference(lpcMaxValueLen.getValue());
        IntByReference lpType = new IntByReference();
        rc = Advapi32.INSTANCE.RegEnumValue(hKey, i, name, lpcchValueName, null,
                lpType, data, lpcbData);
        if (rc != W32Errors.ERROR_SUCCESS) {
            throw new Win32Exception(rc);
        }

        String nameString = Native.toString(name);

        Memory byteData = new Memory(lpcbData.getValue());
        byteData.write(0, data, 0, lpcbData.getValue());

        switch (lpType.getValue()) {
            case WinNT.REG_DWORD: {
                keyValues.put(nameString, byteData.getInt(0));
                break;
            }
            case WinNT.REG_SZ:
            case WinNT.REG_EXPAND_SZ: {
                keyValues.put(nameString, byteData.getString(0, true));
                break;
            }
            case WinNT.REG_BINARY: {
                keyValues.put(nameString, byteData.getByteArray(0, lpcbData.getValue()));
                break;
            }
            case WinNT.REG_MULTI_SZ: {
                Memory stringData = new Memory(lpcbData.getValue());
                stringData.write(0, data, 0, lpcbData.getValue());
                ArrayList<String> result = new ArrayList<>();
                int offset = 0;
                while (offset < stringData.size()) {
                    String s = stringData.getString(offset, true);
                    offset += s.length() * Native.WCHAR_SIZE;
                    offset += Native.WCHAR_SIZE;
                    result.add(s);
                }
                keyValues.put(nameString, result.toArray(new String[result.size()]));
                break;
            }
            default:
                throw new RuntimeException("Unsupported type: " + lpType.getValue());
        }
    }
    return keyValues;
}