How to create bitcoin wallet from mnemonics using bitcoinj (walletappkit) in android - java

I am creating a wallet from mnemonics,for ethereum i have used web3j library for generating mnemonics,address and its private key and now for bitcoin i want to use the same generated mnemonics to generate bitcoin address and its private key for bitcoin i am using Bitcoinj library but not able to get its address and key.
I also tried Walletappkit but its generating address without getting mnemonics so is there any way of using mnemonics in Walletappkit so i can get bitcoin address and sync the bitcoin chain for transactions.
Also is there any way of using walletappkit without syncing and gets bitcoin detail like its balance and transaction info.
Below is the code how I created ethereum wallet and its mnemonic key using web3j and bitcoinj.
val wallet = WalletUtils.generateBip39Wallet("", File(path))
val mnemonics = wallet.mnemonic
// bitcoinj
var seed = DeterministicSeed(wallet.mnemonic, null, "", 1409478661L)
val chain = DeterministicKeyChain.builder().seed(seed).build()
val keyPath = HDUtils.parsePath("M/44H/60H/0H/0/0")
val key = chain.getKeyByPath(keyPath, true)
val privKey = key.privKey
// Web3j
val credentials = Credentials.create(privKey.toString(16))
val eth_address = credentials.address

I'm not sure if I correctly understand what you want to do, but if you want to restore/create a Bitcoinj wallet from a mnemonic seed, then there's an official example for this here:
// Here we restore our wallet from a seed with no passphrase. Also have a look at the BackupToMnemonicSeed.java example that shows how to backup a wallet by creating a mnemonic sentence.
String seedCode = "yard impulse luxury drive today throw farm pepper survey wreck glass federal";
String passphrase = "";
Long creationtime = 1409478661L;
DeterministicSeed seed = new DeterministicSeed(seedCode, null, passphrase, creationtime);
// The wallet class provides a easy fromSeed() function that loads a new wallet from a given seed.
Wallet wallet = Wallet.fromSeed(params, seed, Script.ScriptType.P2PKH);

you can use bitcore.js for generating mnemonics. I am sharing the link of npm package please have a look.
var Mnemonic = require('bitcore-mnemonic');
var code = new Mnemonic(Mnemonic.Words.SPANISH);
code.toString();
var xpriv = code.toHDPrivateKey();

Related

How do I specify the licensing query parameter for the Microsoft Teams API when using the Microsoft Graph SDK for Java?

According to the Licensing and payment requirements for the Microsoft Teams API documentation, I need to include a model query parameter to specify the
licensing and payment model for the Microsoft Teams API. How do I do this when using the Microsoft Graph SDK for Java?
I currently access the Graph API using the com.microsoft.graph.requests.GraphServiceClient class:
public static GraphServiceClient<Request> getGraphClient(#NonNull final AadAuthenticationProperties properties,
#NonNull final String tenantId) {
var credential = new ClientSecretCredentialBuilder().clientId(properties.getCredential().getClientId())
.clientSecret(properties.getCredential().getClientSecret())
.tenantId(tenantId)
.build();
var authProvider = new TokenCredentialAuthProvider(
properties.getAuthorizationClients().get("graph").getScopes(), credential);
final var logger = new DefaultLogger();
logger.setLoggingLevel(LoggerLevel.DEBUG);
return GraphServiceClient.builder().authenticationProvider(authProvider).logger(logger).buildClient();
}
Is there someway that I should alter this client? Would this only be necessary for subscribing to change notifications? While for querying for all object details? While querying for certain particular object details?
Code Snippet that might help, the following is for getAllMessages model A.
You can modify it as per your needs but the underlying logic remains the same.
GraphServiceClient graphClient = new GraphServiceClient( authProvider );
var queryOptions = new List<QueryOption>()
{
new QueryOption("model", "A")
};
var getAllMessages = await graphClient.Users["Alexw#cqons.onMicrosoft.com"].Chats
.GetAllMessages()
.Request( queryOptions )
.GetAsync();
For all future readers, you can query this in Graph Explorer and go to the code snippet section to get the corresponding code snippet.

Get secret name by value from azure Key vault

The idea is that user send me an api-key and I return him a name of his brand. The api key it's a GUID so I can't store it as a secret name.
I am looking for a way to retrieve a secret name by value from a keyvault. That's what my team came up with but it very slow and dramatically increases when adding new secrets to key vault.
public String getClientApiKeyName(final String apiKeyValue) {
for (SecretProperties secretProperties : secretClient.listPropertiesOfSecrets()) {
if (secretProperties.isEnabled()) {
final KeyVaultSecret secretWithValue = secretClient.getSecret(
secretProperties.getName(),
secretProperties.getVersion()
);
if (secretWithValue.getValue().equals(apiKeyValue)) {
return secretWithValue.getName();
}
}
}
return null;
}
Key Vault is designed for your own services secrets. If you are storing your customers' secrets (especially for high-throughput key storage scenarios), consider putting the keys in a database or storage account with encryption, and storing just the master key in Azure Key Vault.
Throttling
If you are seeing error code 429, you should the following are best practices you should implement:
Reduce the number of operations per request.
Reduce the frequency of requests.
Avoid immediate retries.
All requests accrue against your usage limits.
Backoff code example
SecretClientOptions options = new SecretClientOptions()
{
Retry =
{
Delay= TimeSpan.FromSeconds(2),
MaxDelay = TimeSpan.FromSeconds(16),
MaxRetries = 5,
Mode = RetryMode.Exponential
}
};
var client = new SecretClient(new Uri("https://keyVaultName.vault.azure.net"), new DefaultAzureCredential(),options);
//Retrieve Secret
secret = client.GetSecret(secretName);
https://learn.microsoft.com/en-us/azure/key-vault/general/overview-throttling

Accessing AWS parameter store values with custom KMS key

I am trying to read AWS parameters from the parameter store using java, i have created the parameters using a custom encryption key. I dont see a sample code in the internet where its using a custom KMS key , the below is the code i currently have which is working (here we are usingthe default KMS key).
AWSSimpleSystemsManagement client= AWSSimpleSystemsManagementClientBuilder.defaultClient();
GetParametersRequest request= new GetParametersRequest();
request.withNames("test.username","test.password")
.setWithDecryption(true);
This will give the results with default KMS key
Does anyone know how to handle this if we have a custom KMS key
just in case, if somebody looking for this (with Default encryption Key)
protected Parameter getParameterFromSSMByName(String parameterKey)
{
AWSCredentialsProvider credentials = InstanceProfileCredentialsProvider.getInstance();
AWSSimpleSystemsManagement simpleSystemsManagementClient = (AWSSimpleSystemsManagement)((AWSSimpleSystemsManagementClientBuilder)((AWSSimpleSystemsManagementClientBuilder)AWSSimpleSystemsManagementClientBuilder.standard().withCredentials(credentials)).withRegion("us-east-1")).build();
GetParameterRequest parameterRequest = new GetParameterRequest();
parameterRequest.withName(parameterKey).setWithDecryption(Boolean.valueOf(true));
GetParameterResult parameterResult = simpleSystemsManagementClient.getParameter(parameterRequest);
return parameterResult.getParameter();
}
Here is #Extreme's answer as a class with imports and a bit of cleanup:
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.InstanceProfileCredentialsProvider;
import com.amazonaws.services.simplesystemsmanagement.AWSSimpleSystemsManagement;
import com.amazonaws.services.simplesystemsmanagement.AWSSimpleSystemsManagementClientBuilder;
import com.amazonaws.services.simplesystemsmanagement.model.GetParameterRequest;
import com.amazonaws.services.simplesystemsmanagement.model.GetParameterResult;
public class AWSSsmHelper
{
private AWSCredentialsProvider credentials = InstanceProfileCredentialsProvider.getInstance();
private AWSSimpleSystemsManagement simpleSystemsManagementClient =
AWSSimpleSystemsManagementClientBuilder.standard().withCredentials(credentials)).withRegion("us-east-1")).build();
public String getParameterFromSSMByName(String parameterKey) {
GetParameterRequest parameterRequest = new GetParameterRequest();
parameterRequest.withName(parameterKey).setWithDecryption(Boolean.valueOf(true));
GetParameterResult parameterResult = simpleSystemsManagementClient.getParameter(parameterRequest);
return parameterResult.getParameter().getValue();
}
}
For GetParameters API, there's no difference between use default KMS key or custom KMS key. It always works like your code. Just make sure the permission for the credential includes the custom key.
The difference only at PutParameter API, when using a default KMS key, you don't need to specify it, when using a custom KMS key, you set its KeyId to the custom key. The KeyId can be one of following examples:
Key ARN Example arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012
Alias ARN Example - arn:aws:kms:us-east-1:123456789012:alias/MyAliasName
Globally Unique Key ID Example - 12345678-1234-1234-1234-123456789012
Alias Name Example - alias/MyAliasName

Devise confirmation tokens in Java

Can't seem to create a functional way to insert a user from Java for Devise. Currently there are these fields:
"_id",
"access_level",
"confirmation_sent_at",
"confirmation_token",
"confirmed_at",
"email",
"encrypted_password",
"sign_in_count"
I am able to insert a document that counts as a user. The problem is that when I go to:
http://www.mysite.com:3000/users/confirmation?confirmation_token=TOKENHERE
I get a message saying that it's invalid.
EDIT 1:
When I resend confirmation instructions for this user (WHICH GENERATES A NEW TOKEN), the user can be logged into. This confirms my doubts about the token being the problem. How can I port Devise's token generator to Java?
EDIT 2:
When I register on site, it says I should check for a confirmation link. However, if I go into the Mongo shell, manually take out the confirmation token and paste it to site.com/users/confirmation?confirmation_token= then it doesn't work! However, if I actually use the confirmation link I was sent, it works. How can I make a VALID token, all from Java. Please help!
For this quoestion you should refer to this stackoverflow answer and to the Rails API of protect_from_forgery.
The short answer is to disable forgery protection in your controller, but this makes your application vulnerable to CSRF attacks:
skip_before_action :verify_authenticity_token
The better way would be to authenticate with a JSON or XML request as these requests are not protected by CSRF protection. You can find a solution for devise here.
Edit
Monkey patch devise to save unencoded confirmation token. In your config/initializers/devise.rb
module Devise
module Models
module Confirmable
def generate_confirmation_token
raw, enc = Devise.token_generator.generate(self.class, :confirmation_token)
#raw_confirmation_token = raw
self.my_unencoded_column = raw # Patch
self.confirmation_token = enc
self.confirmation_sent_at = Time.now.utc
end
end
end
end
In case anyone else finds themselves trying to get a java or scala app to coexist with a rails app, I hacked up the following. Its in scala but uses java apis so should be easy to read. As far as I can tell it replicates Devise's behavior, and if I hit the confirmation link in the rails app with the raw token rails/devise generates the same encoded string.
import java.security.spec.KeySpec
import javax.crypto.SecretKey
import javax.crypto.SecretKeyFactory
import javax.crypto.spec.PBEKeySpec
import javax.crypto.spec.SecretKeySpec
import javax.crypto.Mac
import javax.xml.bind.DatatypeConverter
import java.util.Base64
// copy functionality from Rails Devise
object TokenGenerator {
// sample values 9exithzwZ8P9meqdVs3K => 54364224169895883e87c8412be5874039b470e26e762cb3ddc37c0bdcf014f5
// 5zNMi6egbyPoDUy2t3NY => 75bd5d53aa36d3fc61ac186b4c6e2be8353e6b39536d3cf846719284e05474ca
private val deviseSecret = sys.env("DEVISE_SECRET")
private val factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1")
val encoder = Base64.getUrlEncoder()
case class TokenInfo(raw: String, encoded: String)
def createConfirmationToken: TokenInfo = {
// copy behavior from rails world. Don't know why it does this
val replacements = Map('l' -> "s", 'I' -> "x", 'O' -> "y", '0' -> "z")
// make a raw key of 20 chars, doesn't seem to matter what they are, just need url valid set
val bytes = new Array[Byte](16)
scala.util.Random.nextBytes(bytes)
val raw = encoder.encodeToString(bytes).take(20).foldLeft(""){(acc, x) => acc ++ replacements.get(x).getOrElse(x.toString)}
TokenInfo(raw, digestForConfirmationToken(raw))
}
private def generateKey(salt: String): Array[Byte] = {
val iter = 65536
val keySize = 512
val spec = new PBEKeySpec(deviseSecret.toCharArray, salt.getBytes("UTF-8"), iter, keySize)
val sk = factory.generateSecret(spec)
val skspec = new SecretKeySpec(sk.getEncoded, "AES")
skspec.getEncoded
}
def sha256HexDigest(s: String, key: Array[Byte]): String = {
val mac = Mac.getInstance("HmacSHA256")
val keySpec = new SecretKeySpec(key, "RAW")
mac.init(keySpec)
val result: Array[Byte] = mac.doFinal(s.getBytes())
DatatypeConverter.printHexBinary(result).toLowerCase
}
private def getDigest(raw: String, salt: String) = sha256HexDigest(raw, generateKey(salt))
// devise uses salt "Devise #{column}", in this case its confirmation_token
def digestForConfirmationToken(raw: String) = getDigest(raw, "Devise confirmation_token")
}

RSA cross platform b/w JAVA & Symbian

1) I am able to Encrypt and Decrypt with my app generated values in symbian with the below values
RInteger iE = RInteger::NewL(0x10001);
RInteger iN = RInteger::NewL(_L8("\xa3\x92\xb7\x34\x82\xbe\x7f\x4f\x8f\xbd\xfb\xd4\xf9\x80\x76\xe0\xa3\xf7\x42\x60\x8e\xe2\xa8\x6b\x76\x22\x67\x0e\x94\xeb\x9b\x3f\xd0\x73\x58\xe0\x23\xbb\x25\x53\x82\x56\x7b\x3e\x05\x57\xc9\x50\x3c\x2d\x6a\x09\x66\x3f\x49\xee\x41\x4c\x4b\x95\x1e\x7d\xb8\xd1\xc5\x40\x0d\xd0\xca\x72\xc8\xf6\x0d\x21\x4f\x63\xc1\x4c\x3b\x93\x94\x1f\x67\x5b\x70\x33\x07\xfd\x4e\x71\x59\x7f\x79\x9b\xd8\xf6\x3b\x35\xe1\x9a\xd3\x27\x43\xdb\x32\xcd\x7b\x78\x40\xd1\x0d\x40\x12\x53\xb7\x19\x66\xca\x5b\xf6\x26\x2a\xea\x4e\xef\xe4\xc8\x41"));
RInteger iD = RInteger::NewL(_L8("\x44\x21\x5a\xff\x9b\x29\x7f\x5b\x83\x32\x8d\x8f\x02\xb1\x18\x52\xae\xd8\xd1\x23\xe8\xbf\xcd\x88\x9c\xf6\xed\x57\xec\x7d\x49\xf7\xc5\x7a\x15\xdd\x9d\xe4\x58\x42\xb5\x3a\x12\x31\x1e\x06\x97\x8a\x3c\xd6\x69\xa1\x2a\x9e\x57\xcb\xce\x14\xda\x32\x6d\x35\xce\x61\x9e\xb2\xaf\x5c\x04\x13\xef\x68\x43\x7e\xe4\x98\xdc\x87\x2e\x7e\x38\x5f\xbd\xe9\x2e\xc1\xf1\x94\xf3\x95\x56\x56\xa4\x78\x26\x70\xa4\x1e\x10\x61\xe9\x45\x25\x1c\xed\xc6\xc0\x1e\xf6\x2c\xa0\x27\xee\x19\x0a\xed\x1c\x76\x33\xc8\x37\xde\x76\x25\x1c\x70\x77\xb1"));
2)Receiving N,E & D values from server then generating Public & Private keys .
(a) Encrypting with public key in app and decrypting in server side successfully.
but
(b) not able to decrypt with private key in my app getting KErrInvalidPadding.
(c) Even with server encrypted message not able to decrypt in app getting same error KErrInvalidPadding.
code:
RInteger iE = RInteger::NewL(0x10001);
RInteger iN = RInteger::NewL(_L8("\x89\x03\xfb\x6d\x15\xf3\x52\xed\x3b\x45\xad\xd3\x21\x6f\x63\x2f\x71\x39\x95\x4a\x56\x31\x33\x7a\xba\x7d\x64\x5e\xd3\x84\x82\xe3\xa8\x10\xb4\xdb\x26\xaa\xb4\xd1\xdf\x58\xc1\x47\x23\x0f\x0c\x75\x63\x1a\x3d\xd0\x55\x4b\x50\xde\x44\xe7\x9f\x4f\xcf\x20\x5c\x89\xfd\x3f\x80\xe0\xff\x8d\x16\xc2\xe9\xf5\x6e\xd3\xab\x17\x79\x53\xd5\x4c\x9c\x30\x35\x7d\x04\xe6\x77\xce\xdd\x99\x12\x90\x6e\xf8\xa0\x46\xd7\xb0\x18\x5b\x7f\x20\x22\xa8\xe4\x35\xb0\xc6\xec\xae\xf9\x3f\x08\x9f\xc3\xaa\x3f\x36\x77\x55\x0b\x5d\x84\x20\x46\xc7"));
RInteger iD = RInteger::NewL(_L8("\x35\xb9\x42\xff\x9d\xe8\xbf\xae\x57\x5c\x55\xf1\x00\x1e\x2d\xd4\xef\x5f\x75\xc3\x25\x12\xbb\xad\xb6\xab\xee\x0c\x24\x81\xc3\xd4\xc2\x14\x72\xe5\xaf\x3e\xa6\x11\xd8\xb2\x73\x6e\x92\x37\x97\x59\xfb\xd6\xd1\x3f\xfc\x01\xc1\x1e\xb6\x03\xdf\xfa\xaa\x2b\x75\x3c\xed\xc6\x8a\x02\x58\xb6\x8d\x6d\xf8\x34\x65\x03\xe3\x8a\x15\x37\xdf\x12\xa8\x18\xff\xce\xfa\x20\x20\xd6\xb7\x1a\x05\x6f\x2c\x04\x13\x58\x62\x94\xe9\xbc\x63\xc8\xd3\xd6\x06\x61\x44\x3e\xac\xe4\x98\x14\x63\xb1\xf7\x06\xaf\x1c\x16\xb6\x5b\x87\x87\x8e\x26\x01"));
TBuf8 <1024>aaaa;
TBuf8 <1024>aOut;
CRSAPublicKey *iPubKey = CRSAPublicKey::NewL(iN,iE);
CRSAPrivateKey *iPriKey = CRSAPrivateKeyStandard::NewL(iN,iD);
CRSAPKCS1v15Encryptor *iEncr = CRSAPKCS1v15Encryptor::NewL(*iPubKey);
CRSAPKCS1v15Decryptor *iDecry = CRSAPKCS1v15Decryptor::NewL(*iPriKey);
TRAPD(err3,iEncr->EncryptL(_L8("Hi"),aaaa));
TRAPD(err2,iDecry->DecryptL(aaaa,aOut)); <-KErrInvalidPadding = -11003;
how to solve this issue anybody suggest me with this.
what do i do
TInt len=iEncr->MaxOutputLength();
iEncr->EncryptL(_L8("Hi"),aaaa);
if (aaaa.Length()<len){
TBuf8<1> t;
t.SetLength(1);t[0]=0;
aaaa.Insert(0,t);
}

Categories

Resources