Android Change password of encrypted Room DB with SQLCipher - android-room

I successfully encrypted my Room DB with SQLCipher.
I now like to give the user to option to change the DB password. So how can I change the SQLCipher password with Room DB?

Found the answer:
database.query("PRAGMA rekey = '$newPassword';", emptyArray())
As complete code example with context:
fun changePassword(previousPassword: String, newPassword: String) {
val passphrase = SQLiteDatabase.getBytes(previousPassword.toCharArray())
val factory = SupportFactory(passphrase)
val database = Room.databaseBuilder(applicationContext, <your_database_class>::class.java, "<database_name>")
.openHelperFactory(factory)
.build()
database.query("PRAGMA rekey = '$newPassword';", emptyArray())
}
There's even no need to close and re-open the database.

Related

Micronaut - Persist WebSocketSession to redis

I am trying to persist my WebsocketSessions on Redis and then succesfully broadcast messages to all my active sessions.
Following the documentation:
https://docs.micronaut.io/latest/guide/index.html#websocket
https://docs.micronaut.io/latest/guide/index.html#sessions
https://micronaut-projects.github.io/micronaut-redis/latest/guide/#sessions
I would expect when I have the following code on my ServerWebSocket, the WebSocket session to be stored automatically on Redis.
#OnOpen
fun onOpen(branchId: Long, session: WebSocketSession) {
session.put(USER_SESSION_KEY, user.id)
session.put(BRANCH_SESSION_KEY, branch.id)
...
session.sendAsync("smth")
}
And then whenever I call the broadcaster, I am expecting the message to be broadcasted to all the open stored-redis-sessions that match the given predicate.
webSocketBroadcaster.broadcastAsync(
webSocketMessage,
shouldSendMessageForSession(order)
)
private fun shouldSendMessageForSession(order: OrdersEntity) = Predicate<WebSocketSession> { session ->
val userId = session[USER_SESSION_KEY, Long::class.java].toNullable() ?: return#Predicate false
val user = userEntityRepository.findById(userId).toNullable() ?: return#Predicate false
val branchId = session[BRANCH_SESSION_KEY, Long::class.java].toNullable() ?: return#Predicate false
return#Predicate order.branchId == branchId && order.canAccessWithUser(user)
}
Sadly this is not happening or I am missing something :( Has anyone found a solution for this?
Is this supported?
If yes, do i need to do something else in order, my broadcaster, to be aware of all the sessions stored on Redis?
Is there a way to serialize|persist a webSocketSession?
Thank you!

Firefox Extension Set Proxy Auth

I am trying to develop and Firefox Extension, which sets a proxy and does some other things after doing that. So i know how to set proxy http and port.
var prefManager = Cc["#mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch);
prefManager.setIntPref("network.proxy.type", 1);
prefManager.setCharPref("network.proxy.http",aProxy[0]);
prefManager.setIntPref("network.proxy.http_port",aProxy[1]);
But i was not able to find the properties for username and password. Seems it will need to be set differently.
Someone can help?
Have you tried saving the passwords using nsILoginManager? In Firefox, password for proxies are handled like any other password.
let LoginInfo = new Components.Constructor("#mozilla.org/login-manager/loginInfo;1", Components.interfaces.nsILoginInfo, "init");
let loginInfo = new LoginInfo(
hostname,
null,
realm,
user,
password,
'',
''
);
let loginManager = Components.classes["#mozilla.org/login-manager;1"].getService(Components.interfaces.nsILoginManager);
loginManager.addLogin(loginInfo);
Proxies don't have a scheme, so I've seen code in Firefox do something like this (code from https://hg.mozilla.org/mozilla-central/file/69d61e42d5df/toolkit/components/passwordmgr/nsLoginManagerPrompter.js#l1400):
// Proxies don't have a scheme, but we'll use "moz-proxy://"
// so that it's more obvious what the login is for.
var idnService = Cc["#mozilla.org/network/idn-service;1"].
getService(Ci.nsIIDNService);
hostname = "moz-proxy://" +
idnService.convertUTF8toACE(info.host) +
":" + info.port;
realm = aAuthInfo.realm;
if (!realm)
realm = hostname;
I think it's just for readability (when the user opens the password manager), but it shouldn't be required.
P.S.: There's also a preference, signon.autologin.proxy, that makes Firefox not prompt for authentication if a password is saved.

Google Apps Jdbc - Connection Issue

I am trying to connect to a MySQL server using Jdbc for Google Apps and getting an error as follows:
Failed to establish a database connection. Check connection string,
username and password. (line 10, file "dbadmin")
The following is a snipet of the code I am using:
var address = 'w.x.y.z';
var user = 'user';
var userPwd = 'password';
var db = 'dbname';
var dbUrl = 'jdbc:mysql://' + address + '/' + db;
var conn = Jdbc.getConnection(dbUrl, user, userPwd);
I have successfully connected to the Database from my own computer using both the IP and Hostname. I have confirmed the server should be accepted connections from ALL IPs for that account, and confirmed the ruleset is working by removing the whitelisting and adding it back again.
I am basically out of troubleshooting ideas of what is going on. What am I doing wrong, or what is wrong with Google?
A typical way to establish JDBC connection is as follows:
String url = "jdbc:mysql://hostname:3306/mydb";
String username = "username";
String password = "password"
Connection conn = DriverManager.getConnection(url, username, password);
You can refer to this for more detailed information.

ServiceStack Accessing Session Directly

I'm having trouble getting direct manipulation of sessions working properly.
Using some code from the source and a tip from Demis, I've put together something in our unit test client to auth the user and then recover the session.
The AuthResponse I'm getting from the service has a SessionId of 533, which results in a constructed urn of "urn:iauthsession:533", whereas the urn in the Redis cache is "urn:iauthsession:sbQBLwb1WpRj8DqQ7EdL", so obviously, the thing being passed to the urn builder in the running code is not simply the session id (or the overload being used is not what I think it is).
Here's the code we're using in our test base class to try to recover the session from the auth call:
var client = new JsonServiceClient(ServiceTestAppHost.BaseUrl)
{
UserName = userName,
Password = password,
AlwaysSendBasicAuthHeader = true
};
var response = client.Post<AuthResponse>("/auth/basic", new Auth() { UserName = userName, Password = password, RememberMe = true });
var sessionKey = IdUtils.CreateUrn<IAuthSession>(response.SessionId);
var session = _appHost.TryResolve<ICacheClient>().Get<SsoUserSession>(sessionKey);
Any idea why the constructed urn is not matching?
This should now be fixed with this commit which is available in v4.0.22 that's now available on MyGet.

Windows Service Setting user account

I want to set the user account for Windows Service even before installing.
I am doing it by adding code in project installer.
this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.User;
this.serviceProcessInstaller1.Password = ConfigurationSettings.AppSettings["password"];
this.serviceProcessInstaller1.Username = ConfigurationSettings.AppSettings["username"];
Still its prompting for Username and password. Looks like the configuration file is not getting ready by the time the installation is done.
How I can i pull the username and password from configuration file instead of hardcoding it?
Well, I'm at a loss to say why the AppSettings values are not readable in the traditional manner while the installer is running. I tried it myself and ran into the same problem you are having. However, I was able to get around the problem by loading the configuration file as a regular XML file and reading it that way. Try this:
XmlDocument doc = new XmlDocument();
doc.Load(Assembly.GetExecutingAssembly().Location + ".config");
XmlElement appSettings = (XmlElement)doc.DocumentElement.GetElementsByTagName("appSettings")[0];
string username = null;
string password = null;
foreach (XmlElement setting in appSettings.GetElementsByTagName("add"))
{
string key = setting.GetAttribute("key");
if (key == "username") username = setting.GetAttribute("value");
if (key == "password") password = setting.GetAttribute("value");
}
serviceProcessInstaller1.Account = ServiceAccount.User;
serviceProcessInstaller1.Username = username;
serviceProcessInstaller1.Password = password;

Resources