Search in sources :

Example 1 with SeedCalculator

use of io.github.novacrypto.bip39.SeedCalculator in project popstellar by dedis.

the class Wallet method exportSeed.

/**
 * Method that encode the seed into a form that is easier for humans to securely back-up and
 * retrieve.
 *
 * @return an array of words: mnemonic sentence representing the seed for the wallet in case that
 *     the key set manager is not init return a empty array.
 * @throws GeneralSecurityException if an error occurs
 */
public String[] exportSeed() throws GeneralSecurityException {
    SecureRandom random = new SecureRandom();
    byte[] entropy = random.generateSeed(Words.TWELVE.byteLength());
    List<CharSequence> words = new LinkedList<>();
    MnemonicGenerator generator = new MnemonicGenerator(English.INSTANCE);
    generator.createMnemonic(entropy, words::add);
    String[] wordsFiltered = words.stream().filter(// Filter out spaces
    s -> !s.equals(" ")).map(CharSequence::toString).toArray(String[]::new);
    Log.d(TAG, "the array of word generated:" + Arrays.toString(wordsFiltered));
    seed = aead.encrypt(new SeedCalculator().calculateSeed(String.join("", words), ""), new byte[0]);
    Log.d(TAG, "ExportSeed: new seed initialized: " + Utils.bytesToHex(seed));
    return wordsFiltered;
}
Also used : SeedCalculator(io.github.novacrypto.bip39.SeedCalculator) SecureRandom(java.security.SecureRandom) MnemonicGenerator(io.github.novacrypto.bip39.MnemonicGenerator) LinkedList(java.util.LinkedList)

Example 2 with SeedCalculator

use of io.github.novacrypto.bip39.SeedCalculator in project popstellar by dedis.

the class Wallet method importSeed.

/**
 * Method that allow import mnemonic seed.
 *
 * @param words a String.
 */
public void importSeed(@NonNull String words) throws SeedValidationException, GeneralSecurityException {
    try {
        MnemonicValidator.ofWordList(English.INSTANCE).validate(words);
    } catch (InvalidChecksumException | InvalidWordCountException | WordNotFoundException | UnexpectedWhiteSpaceException e) {
        throw new SeedValidationException(e);
    }
    seed = aead.encrypt(new SeedCalculator().calculateSeed(words, ""), new byte[0]);
    Log.d(TAG, "ImportSeed: new seed: " + Utils.bytesToHex(seed));
}
Also used : UnexpectedWhiteSpaceException(io.github.novacrypto.bip39.Validation.UnexpectedWhiteSpaceException) SeedValidationException(com.github.dedis.popstellar.utility.error.keys.SeedValidationException) SeedCalculator(io.github.novacrypto.bip39.SeedCalculator) WordNotFoundException(io.github.novacrypto.bip39.Validation.WordNotFoundException) InvalidWordCountException(io.github.novacrypto.bip39.Validation.InvalidWordCountException) InvalidChecksumException(io.github.novacrypto.bip39.Validation.InvalidChecksumException)

Example 3 with SeedCalculator

use of io.github.novacrypto.bip39.SeedCalculator in project moera-node by MoeraOrg.

the class NodeNameController method post.

@PostMapping
@Admin
@Transactional
public RegisteredNameSecret post(@Valid @RequestBody NameToRegister nameToRegister, HttpServletRequest request) {
    if (!Rules.isNameValid(nameToRegister.getName())) {
        throw new OperationFailure("nameToRegister.name.invalid");
    }
    log.info("POST /node-name (name = '{}')", nameToRegister.getName());
    Options options = requestContext.getOptions();
    if (options.getUuid("naming.operation.id") != null) {
        throw new OperationFailure("naming.operation-pending");
    }
    RegisteredNameSecret secretInfo = new RegisteredNameSecret();
    secretInfo.setName(nameToRegister.getName());
    KeyPair signingKeyPair;
    try {
        SecureRandom random = new SecureRandom();
        byte[] entropy = new byte[Words.TWENTY_FOUR.byteLength()];
        ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec(Rules.EC_CURVE);
        KeyFactory keyFactory = KeyFactory.getInstance("EC", "BC");
        BigInteger d = BigInteger.ZERO;
        while (d.equals(BigInteger.ZERO)) {
            random.nextBytes(entropy);
            StringBuilder mnemonic = new StringBuilder();
            new MnemonicGenerator(English.INSTANCE).createMnemonic(entropy, mnemonic::append);
            byte[] seed = new SeedCalculator(JavaxPBKDF2WithHmacSHA512.INSTANCE).calculateSeed(mnemonic.toString(), "");
            secretInfo.setSecret(Util.base64encode(entropy));
            secretInfo.setMnemonic(mnemonic.toString().split(" "));
            d = new BigInteger(1, seed).remainder(ecSpec.getN());
        }
        ECPoint q = ecSpec.getG().multiply(d);
        ECPublicKeySpec pubSpec = new ECPublicKeySpec(q, ecSpec);
        ECPublicKey publicUpdatingKey = (ECPublicKey) keyFactory.generatePublic(pubSpec);
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC", "BC");
        keyPairGenerator.initialize(ecSpec, random);
        signingKeyPair = keyPairGenerator.generateKeyPair();
        namingClient.register(nameToRegister.getName(), getNodeUri(request), publicUpdatingKey, (ECPrivateKey) signingKeyPair.getPrivate(), (ECPublicKey) signingKeyPair.getPublic(), options);
    } catch (GeneralSecurityException e) {
        throw new CryptoException(e);
    }
    return secretInfo;
}
Also used : Options(org.moera.node.option.Options) KeyPair(java.security.KeyPair) GeneralSecurityException(java.security.GeneralSecurityException) SeedCalculator(io.github.novacrypto.bip39.SeedCalculator) SecureRandom(java.security.SecureRandom) KeyPairGenerator(java.security.KeyPairGenerator) ECPoint(org.bouncycastle.math.ec.ECPoint) OperationFailure(org.moera.node.model.OperationFailure) ECPublicKeySpec(org.bouncycastle.jce.spec.ECPublicKeySpec) RegisteredNameSecret(org.moera.node.model.RegisteredNameSecret) ECPublicKey(java.security.interfaces.ECPublicKey) ECParameterSpec(org.bouncycastle.jce.spec.ECParameterSpec) BigInteger(java.math.BigInteger) MnemonicGenerator(io.github.novacrypto.bip39.MnemonicGenerator) CryptoException(org.moera.commons.crypto.CryptoException) KeyFactory(java.security.KeyFactory) PostMapping(org.springframework.web.bind.annotation.PostMapping) Admin(org.moera.node.auth.Admin) Transactional(javax.transaction.Transactional)

Example 4 with SeedCalculator

use of io.github.novacrypto.bip39.SeedCalculator in project moera-node by MoeraOrg.

the class NodeNameController method put.

@PutMapping
@Admin
@Transactional
public Result put(@Valid @RequestBody RegisteredNameSecret registeredNameSecret, HttpServletRequest request) {
    log.info("PUT /node-name");
    Options options = requestContext.getOptions();
    if (options.getUuid("naming.operation.id") != null) {
        throw new OperationFailure("naming.operation-pending");
    }
    String nodeName = registeredNameSecret.getName() != null ? registeredNameSecret.getName() : options.nodeName();
    if (ObjectUtils.isEmpty(nodeName)) {
        throw new ValidationFailure("node-name.name-absent");
    }
    if ((registeredNameSecret.getMnemonic() == null || registeredNameSecret.getMnemonic().length == 0) && ObjectUtils.isEmpty(registeredNameSecret.getSecret())) {
        throw new ValidationFailure("registeredNameSecret.empty");
    }
    String mnemonic;
    if (!ObjectUtils.isEmpty(registeredNameSecret.getSecret())) {
        byte[] entropy = Util.base64decode(registeredNameSecret.getSecret());
        StringBuilder buf = new StringBuilder();
        new MnemonicGenerator(English.INSTANCE).createMnemonic(entropy, buf::append);
        mnemonic = buf.toString();
    } else {
        mnemonic = String.join(" ", registeredNameSecret.getMnemonic());
    }
    byte[] seed = new SeedCalculator(JavaxPBKDF2WithHmacSHA512.INSTANCE).calculateSeed(mnemonic, "");
    try {
        KeyFactory keyFactory = KeyFactory.getInstance("EC", "BC");
        ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec(Rules.EC_CURVE);
        BigInteger d = new BigInteger(1, seed).remainder(ecSpec.getN());
        ECPrivateKeySpec privateKeySpec = new ECPrivateKeySpec(d, ecSpec);
        ECPrivateKey privateUpdatingKey = (ECPrivateKey) keyFactory.generatePrivate(privateKeySpec);
        ECPrivateKey privateSigningKey = null;
        ECPublicKey signingKey = null;
        if (registeredNameSecret.getName() != null) {
            SecureRandom random = new SecureRandom();
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC", "BC");
            keyPairGenerator.initialize(ecSpec, random);
            KeyPair signingKeyPair = keyPairGenerator.generateKeyPair();
            privateSigningKey = (ECPrivateKey) signingKeyPair.getPrivate();
            signingKey = (ECPublicKey) signingKeyPair.getPublic();
        }
        namingClient.update(nodeName, getNodeUri(request), privateUpdatingKey, privateSigningKey, signingKey, options);
    } catch (GeneralSecurityException e) {
        throw new CryptoException(e);
    } catch (OperationFailure of) {
        throw new OperationFailure("node-name." + of.getErrorCode());
    }
    return Result.OK;
}
Also used : Options(org.moera.node.option.Options) ECPrivateKey(java.security.interfaces.ECPrivateKey) KeyPair(java.security.KeyPair) ECPrivateKeySpec(org.bouncycastle.jce.spec.ECPrivateKeySpec) GeneralSecurityException(java.security.GeneralSecurityException) SeedCalculator(io.github.novacrypto.bip39.SeedCalculator) SecureRandom(java.security.SecureRandom) KeyPairGenerator(java.security.KeyPairGenerator) OperationFailure(org.moera.node.model.OperationFailure) ValidationFailure(org.moera.node.model.ValidationFailure) ECPublicKey(java.security.interfaces.ECPublicKey) ECParameterSpec(org.bouncycastle.jce.spec.ECParameterSpec) BigInteger(java.math.BigInteger) MnemonicGenerator(io.github.novacrypto.bip39.MnemonicGenerator) CryptoException(org.moera.commons.crypto.CryptoException) KeyFactory(java.security.KeyFactory) PutMapping(org.springframework.web.bind.annotation.PutMapping) Admin(org.moera.node.auth.Admin) Transactional(javax.transaction.Transactional)

Aggregations

SeedCalculator (io.github.novacrypto.bip39.SeedCalculator)4 MnemonicGenerator (io.github.novacrypto.bip39.MnemonicGenerator)3 SecureRandom (java.security.SecureRandom)3 BigInteger (java.math.BigInteger)2 GeneralSecurityException (java.security.GeneralSecurityException)2 KeyFactory (java.security.KeyFactory)2 KeyPair (java.security.KeyPair)2 KeyPairGenerator (java.security.KeyPairGenerator)2 ECPublicKey (java.security.interfaces.ECPublicKey)2 Transactional (javax.transaction.Transactional)2 ECParameterSpec (org.bouncycastle.jce.spec.ECParameterSpec)2 CryptoException (org.moera.commons.crypto.CryptoException)2 Admin (org.moera.node.auth.Admin)2 OperationFailure (org.moera.node.model.OperationFailure)2 Options (org.moera.node.option.Options)2 SeedValidationException (com.github.dedis.popstellar.utility.error.keys.SeedValidationException)1 InvalidChecksumException (io.github.novacrypto.bip39.Validation.InvalidChecksumException)1 InvalidWordCountException (io.github.novacrypto.bip39.Validation.InvalidWordCountException)1 UnexpectedWhiteSpaceException (io.github.novacrypto.bip39.Validation.UnexpectedWhiteSpaceException)1 WordNotFoundException (io.github.novacrypto.bip39.Validation.WordNotFoundException)1