How to get from private key and seed phrase to account address? - hash

This info are of a metamask dummy account. Does anyone know the process to get the hash_mm from seed and/or private_key?
seed = "else wrist ..."
private_key = 'd75d1...'
hash_mm = '0x0411CAb45688e0815B8c36813d148E1E43dDa868'

See https://ethereum.stackexchange.com/a/11272/97038
const secp256k1 = require('secp256k1');
const pubKey = secp256k1.publicKeyCreate(private_key, false).slice(1);

Related

C# .NET Framework 4.7.2 in VS 2019 - keep out my clientID and client secret / gitignore / Key Vault

I am a new to #C, therefore excuse my question, which will be probably very easy to you. I am trying to get my clientID, clientSecret and tenantID out of the main source control, but I am not sure at all how to do that. I have seen some methods for .NET Core with Connected Services in Visual Studio, but this is not really available for .NET Framework 4.7.2. I am not confident in setting the config file neither. I have created a resource group on Azure Portal, but I am not sure how to get this key vault working.
The code below represents a working code acquiring a token, the issue I have is to hide those hardcoded strings.
Many thanks for your answer
private static string GetToken()
{
string clientID = "xxxad43f-c825-491f-9130-8cc4da1d1111";
string clientSecret = "dRbIT5Wn4#u=55L#fLnYRNuDYrFD#111";
string tenantID = "4ae48b41-0137-4599-8661-fc641fe77111";
var app = ConfidentialClientApplicationBuilder
.Create(clientID)
.WithClientSecret(clientSecret)
.WithAuthority(new Uri($"https://login.microsoftonline.com/{tenantID}/oauth2/v2.0/token"))
.Build();
var ApiID = "api://dddd-api";
var scopes = new[] { ApiID + "/.default" };
var result = app.AcquireTokenForClient(scopes).ExecuteAsync().Result;
if (result == null)
throw new Exception("Could not acquire token");
return result.AccessToken;
}
You can set the value as environment variables and use Environment.GetEnvironmentVariable("<variable name>") to get them.
string clientID = Environment.GetEnvironmentVariable("AZURE_CLIENT_ID");
string clientSecret = Environment.GetEnvironmentVariable("AZURE_CLIENT_SECRET");
string tenantID = Environment.GetEnvironmentVariable("AZURE_TENANT_ID");

Securely use Connection string of MongoAtlas in Node.Js to connect to MongoDB

I am trying to connect to MongoAtlas for a local project. Is there any way of breaking down the connection string into variables like database name, database password, database hostname, etc, that has been given to me in 'Connect your Application' in the connect part(Driver settings:- Node 3.0+). Although I could use the driver example they have given to me I would like to do it with mongoose.connect(). Can anyone tell as to what should be done?
Yes you can do that using Template_literals :
process.env.uName = 'username'
process.env.password = 'password'
process.env.server = 'cluster123-abcde.mongodb.net'
const uName = process.env.uName
const password = process.env.password
const server = process.env.server
const url = `mongodb+srv://${uName}:${password}#${server}/test?retryWrites=true&w=majority`
mongoose.connect(url, { useNewUrlParser: true });
Note : If you're using any cloud provider then they're having something like aws-secrets-manager or aws-systems-manager-parameter-store to store environment variables in a secured manner. You can get those values from here & set it up on runtime once before connection is established. Or traditionally you can find someway to populate environment variables during deployment time.
If you need it in more secured manner, then you can encrypt your complete connection string & store encrypted string + key somewhere & while connection creation decrypt those to make a connection, Check this :
const crypto = require('crypto'); // Take use of crypto library from Node.Js
const secretKey = 'somestringlengthof32';
function decrypt(text) {
let res = null;
try {
const textParts = text.split(':');
const iv = Buffer.from(textParts.shift(), 'hex');
const encryptedText = Buffer.from(textParts.join(':'), 'hex');
const decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(secretKey), iv);
let decrypted = decipher.update(encryptedText);
decrypted = Buffer.concat([decrypted, decipher.final()]);
res = decrypted.toString();
} catch (err) {
logger.error('Error in decrypt func ::', err);
}
return res;
}
function encrypt(text) {
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(secretKey), iv);
let encrypted = cipher.update(text);
encrypted = Buffer.concat([encrypted, cipher.final()]);
return `${iv.toString('hex')}:${encrypted.toString('hex')}`;
}
const urlString = 'mongodb+srv://username:password#cluster123-abcde.mongodb.net/test?retryWrites=true&w=majority'
const encryptedString = encrypt(urlString)
console.log(encryptedString) // Store this string & secretKey somewhere in secured place & use these while connection creation by calling decrypt function
console.log(decrypt(encryptedString))

Keycloak One Time Use token

We have a requirement to generate one time use tokens and use it in password reset emails.
Does Keycloak provide any standard API´s to generate and Validate one time tokens?.
We are using OIDC
Rsource Owner Password Credentials Grant (Direct Access Grants for authentication.
You can implement customized Action Token SPI, and Required Action SPI. Which would generate required token and then challenge user for them.
https://www.keycloak.org/docs/7.0/server_development/index.html#_action_token_spi
Anatomy of Action Token
nonce - Random nonce to guarantee uniqueness of use if the operation can only be executed once (optional). This is a random string that your application must generate.
Here’s an example of Java Servlet code that generates the URL to establish the account link.
​KeycloakSecurityContext session = (KeycloakSecurityContext) httpServletRequest.getAttribute(KeycloakSecurityContext.class.getName());
​AccessToken token = session.getToken();
​String clientId = token.getIssuedFor();
​String nonce = UUID.randomUUID().toString();
​MessageDigest md = null;
​try {
​md = MessageDigest.getInstance("SHA-256");
​} catch (NoSuchAlgorithmException e) {
​throw new RuntimeException(e);
​}
​String input = nonce + token.getSessionState() + clientId + provider;
​byte[] check = md.digest(input.getBytes(StandardCharsets.UTF_8));
​String hash = Base64Url.encode(check);
​request.getSession().setAttribute("hash", hash);
​String redirectUri = ...;
​String accountLinkUrl = KeycloakUriBuilder.fromUri(authServerRootUrl)
​.path("/auth/realms/{realm}/broker/{provider}/link")
​.queryParam("nonce", nonce)
​.queryParam("hash", hash)
​.queryParam("client_id", clientId)
​.queryParam("redirect_uri", redirectUri).build(realm, provider).toString();

How do I create an AlertsClient from an Azure Active Directory secret? [duplicate]

My company is looking into reporting on Azure. We only want our customers to give us read only credentials for us to use. I did some research and it looks like Azure Active Directory does just that. So I'm looking to authenticate using a read only Azure Directory Application.
To get me started I was following this blog on using the Management API via Azure Active Directory.
https://msdn.microsoft.com/en-us/library/azure/dn722415.aspx
Aside from the approach show being very unfriendly, it doesn't work =(
I get this error after logging in as a global administrator:
"AADSTS90014: The request body must contain the following parameter: 'client_secret or client_assertion'."
Did some research and found this style of authentication was for native app and NOT web apps (despite what the blog post saying other wise..). So I made a tweak. My GetAuthorizationHeader now looks like this:
private static string GetAuthorizationHeader()
{
AuthenticationResult result = null;
var context = new AuthenticationContext("https://login.windows.net/" + ConfigurationManager.AppSettings["tenantId"]);
string clientId = ConfigurationManager.AppSettings["clientId"];
string clientSecret = ConfigurationManager.AppSettings["clientSecret"];
ClientCredential clientCred = new ClientCredential(clientId, clientSecret);
var thread = new Thread(() =>
{
result = context.AcquireToken(
"https://management.core.windows.net/",
clientCred);
});
thread.SetApartmentState(ApartmentState.STA);
thread.Name = "AquireTokenThread";
thread.Start();
thread.Join();
if (result == null)
{
throw new InvalidOperationException("Failed to obtain the JWT token");
}
string token = result.AccessToken;
return token;
}
I am able to get the Access Token (yay). But now when I try to use this with the Azure Management library client I get this error:
"ForbiddenError: The server failed to authenticate the request. Verify that the certificate is valid and is associated with this subscription."
I double checked my permissions in my application. It looked good. I tried giving full access to everything to see if that would have made a difference.
I double checked my tenantId, clientId, and subscriptionId, all looked good.
I made sure the subscription I'm using is pointed to the AD my application is in.
I tried making a new secret key.
My guess is this is the issue:
However in this UI I am unable to select any values for that property. I'm unsure if this is the result of a bug or an unfinished feature.
Am I missing something here?
Thanks
Here's my full code for reference:
class Program
{
static void Main(string[] args)
{
var token = GetAuthorizationHeader();
var credential = new TokenCloudCredentials(ConfigurationManager.AppSettings["subscriptionId"], token);
using (var computeClient = new ComputeManagementClient(credential))
{
var images = computeClient.VirtualMachineOSImages.List();
}
}
private static string GetAuthorizationHeader()
{
AuthenticationResult result = null;
var context = new AuthenticationContext("https://login.windows.net/" + ConfigurationManager.AppSettings["tenantId"]);
string clientId = ConfigurationManager.AppSettings["clientId"];
string clientSecret = ConfigurationManager.AppSettings["clientSecret"];
ClientCredential clientCred = new ClientCredential(clientId, clientSecret);
var thread = new Thread(() =>
{
result = context.AcquireToken(
"https://management.core.windows.net/",
clientCred);
});
thread.SetApartmentState(ApartmentState.STA);
thread.Name = "AquireTokenThread";
thread.Start();
thread.Join();
if (result == null)
{
throw new InvalidOperationException("Failed to obtain the JWT token");
}
string token = result.AccessToken;
return token;
}
}
EDIT:
Progress has been made. As I discussed with Gaurav, I needed to ditch the Azure Management Library because as of right now it does not seem to support Azure Resource Manager (ARM) API! So instead I did raw web requests. And it works as intended. If I remove role access off my AD Application I get access denied. When I have it I get back data.
One thing I'm not sure about is making it so my application is auto-adding to new resources.
Also, Is there a way to list Resource Groups that are accessible for my AD Application?
New code:
class Program
{
static void Main(string[] args)
{
var token = GetAuthorizationHeader();
string subscriptionId = ConfigurationManager.AppSettings["subscriptionId"];
string resourceGroupName = ConfigurationManager.AppSettings["resourceGroupName"];
var uriListMachines = string.Format("https://management.azure.com/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Compute/virtualmachines?api-version=2015-05-01-preview", subscriptionId, resourceGroupName);
var t = WebRequest.Create(uriListMachines);
t.ContentType = "application/json";
t.Headers.Add("Authorization", "Bearer " + token);
var response = (HttpWebResponse)t.GetResponse();
string result = "";
using (var reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
}
//Original Attempt:
//var credential = new TokenCloudCredentials(ConfigurationManager.AppSettings["subscriptionId"], token);
//using (var client = CloudContext.Clients.CreateComputeManagementClient(credential))
//{
// var images = client.VirtualMachineVMImages.List();
//}
}
private static string GetAuthorizationHeader()
{
AuthenticationResult result = null;
var context = new AuthenticationContext("https://login.windows.net/" + ConfigurationManager.AppSettings["tenantId"]);
string clientId = ConfigurationManager.AppSettings["clientId"];
string clientSecret = ConfigurationManager.AppSettings["clientSecret"];
ClientCredential clientCred = new ClientCredential(clientId, clientSecret);
var thread = new Thread(() =>
{
result = context.AcquireToken(
"https://management.core.windows.net/",
clientCred);
});
thread.SetApartmentState(ApartmentState.STA);
thread.Name = "AquireTokenThread";
thread.Start();
thread.Join();
if (result == null)
{
throw new InvalidOperationException("Failed to obtain the JWT token");
}
string token = result.AccessToken;
return token;
}
}
EDIT EDIT:
I figured out my hung up. Resources created in the OLD portal will get it's own distinct resource group.
From what I can tell you can not add a resource made in the old portal existing resource group (boooo). Resources created in the new portal will be able to assign the resource to an existing group (aka one that gives a role access to my AD Application).
This is such a mess! But at least I know what is going on now.
I believe you're on the right track as to why you're running into this problem.
Here's what's happening:
Essentially permission to execute Service Management API is a delegated permission and not an application permission. In other words, the API is executed in context of the user for which the token is acquired. Now you are getting this token for your application (specified by client id/secret). However your application doesn't have access to your Azure Subscription because the user record created for this application in your Azure AD is of type Service Principal. Since this Service Principal doesn't have access to your Azure Subscription, you're getting this Forbidden Error (I must say that the error is misleading because you're not using certificate at all).
There are a few things you could do:
Switch to Azure Resource Manager (ARM) API - ARM API is the next generation of Service Management API (SM API) and Azure is moving towards this direction only. It exclusively works off of Azure AD token. If possible, make use of that to manage your Azure resources (though you need to keep in mind that as of today not all Azure resources can be managed through ARM API). They way you do it is take your Service Principal and assign it to a particular role using new Azure Portal. Please see this link for more details on this: https://azure.microsoft.com/en-in/documentation/articles/resource-group-create-service-principal-portal/.
Use X509 Certificate - You can always use X509 Certificate based authorization to authorize your SM API requests. Please see this link for more details on that: https://msdn.microsoft.com/en-us/library/azure/ee460782.aspx#bk_cert. The downside of this approach is that the application (or whosoever has access to this certificate) will get full access to your Azure Subscription and can do everything there (including deleting resources).
Acquire token for a user instead of an application - This is another approach you can take. Essentially ask your users to login into Azure AD through your console application and acquire token for that user. Again, please keep in mind that this user must be a Co-Admin in your Azure Subscription and will have full access to your Azure Subscription as with SM API there's no concept of Role-based access control.

How to generate password policy based password in OIM 11gr2ps2

I am creating a event handler to modify user password using OIM UserManager API. But now I need to consider password policy and then generate new password that is compatible with the password policy defined in OIM.
Can you please point to some APIs and Methods which can help here?
import oracle.idm.common.ipf.api.password.RandomPasswordGenerator;
import oracle.idm.common.ipf.api.password.RandomPasswordGeneratorImpl;
The classes above actually gives handle on the randomly generated password that I was looking for. The code below shows the implementation for the same.
PasswordPolicyInfo passwordPolicyInfo = ((PasswordMgmtService)Platform.getService(PasswordMgmtService.class)).getApplicablePasswordPolicy(entityId, Boolean.valueOf(false));
RandomPasswordGenerator randomPasswordGenerator = new RandomPasswordGeneratorImpl();
OimPasswordPolicy policy = new OimPasswordPolicy(Utils.getIpfPasswordPolicyInfoVO(passwordPolicyInfo));
policy.setId(passwordPolicyInfo.getId());
policy.setName(passwordPolicyInfo.getName());
char[] generatedPassword = randomPasswordGenerator.generatePassword(policy, null);
Alternatively by using below OIM API's,you can generate password and also validate it against any policy in OIM:
import oracle.iam.passwordmgmt.api.PasswordMgmtService;
import oracle.iam.passwordmgmt.domain.generator.RandomPasswordGeneratorImpl;
Here is the snippet:
RandomPasswordGeneratorImpl randomPasswordGenerator = new RandomPasswordGeneratorImpl();
UserRepository userRepository = new DBUserRepository();
UserInfo usrInfo = userRepository.getUserAndManagerInfo(usrLogin);
String generatedPassword = new String(randomPasswordGenerator.generatePassword(Utils.getUser(usrInfo)));
PasswordMgmtService passMgmt = Platform.getService(PasswordMgmtService.class);
ValidationResult result = passMgmt.validatePasswordAgainstPolicy(generatedPassword.toCharArray(), Utils.getUser(usrInfo), Locale.getDefault());
You can use PasswordMgmtService api provided by OIM.
You can use below method in you password generation logic in your event handler code.
PasswordPolicyDescription getApplicablePasswordPolicyDescription(java.lang.String userID)
In the PasswordPolicyDescription object you have all properties which were configured while creating Password Policy.