-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(mnemonic): js doesnt handle List and swift doesnt handle Array t…
…his is the solution
- Loading branch information
1 parent
3f32662
commit 9cacf48
Showing
7 changed files
with
2,160 additions
and
2,135 deletions.
There are no files selected for viewing
50 changes: 40 additions & 10 deletions
50
...ic-encryption/src/commonMain/kotlin/io/iohk/atala/prism/apollo/derivation/MnemonicCode.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,21 +1,51 @@ | ||
package io.iohk.atala.prism.apollo.derivation | ||
|
||
import kotlin.js.ExperimentalJsExport | ||
import kotlin.js.JsExport | ||
import io.iohk.atala.prism.apollo.hashing.SHA256 | ||
|
||
/** | ||
* A model representing the Mnemonic Code | ||
* | ||
* @exception MnemonicLengthException in case it is not 24 words | ||
*/ | ||
@OptIn(ExperimentalJsExport::class) | ||
@JsExport | ||
data class MnemonicCode | ||
@Throws(MnemonicLengthException::class) | ||
constructor(val words: List<String>) { | ||
init { | ||
if (words.size % 3 != 0) { | ||
throw MnemonicLengthException("Can't create a DID from mnemonic that is not dividable by 3") | ||
|
||
data class MnemonicCode constructor(val words: List<String>) { | ||
fun toMnemonic(entropy: ByteArray): List<String> { | ||
if (entropy.size % 4 > 0) { | ||
throw Exception("Entropy length not multiple of 32 bits.") | ||
} | ||
if (entropy.isEmpty()) { | ||
throw Exception("Entropy is empty.") | ||
} | ||
|
||
val sha = SHA256() | ||
sha.update(entropy) | ||
val hash = sha.digest() | ||
val checksumLengthBits = entropy.size / 4 | ||
val checksum = hash[0].toInt() ushr (8 - checksumLengthBits) | ||
|
||
val concatBits = BooleanArray(entropy.size * 8 + checksumLengthBits) | ||
for (i in entropy.indices) { | ||
for (j in 0 until 8) { | ||
concatBits[i * 8 + j] = entropy[i].toInt() and (1 shl (7 - j)) != 0 | ||
} | ||
} | ||
for (i in 0 until checksumLengthBits) { | ||
concatBits[entropy.size * 8 + i] = checksum and (1 shl (checksumLengthBits - i - 1)) != 0 | ||
} | ||
|
||
val words = ArrayList<String>() | ||
val nwords = concatBits.size / 11 | ||
for (i in 0 until nwords) { | ||
var index = 0 | ||
for (j in 0 until 11) { | ||
index = index shl 1 | ||
if (concatBits[i * 11 + j]) { | ||
index = index or 0x1 | ||
} | ||
} | ||
words.add(this.words[index]) // Assuming wordList is a list of words according to BIP-39 | ||
} | ||
|
||
return words | ||
} | ||
} |
Oops, something went wrong.