Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions rust/pkg/cardano_serialization_lib.js.flow
Original file line number Diff line number Diff line change
Expand Up @@ -3381,6 +3381,12 @@ declare export class PrivateKey {
*/
static generate_ed25519extended(): PrivateKey;

/**
* @param {string} bech_str
* @returns {PrivateKey}
*/
static from_bech32(bech_str: string): PrivateKey;

/**
* @returns {string}
*/
Expand Down
19 changes: 19 additions & 0 deletions rust/src/crypto.rs
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,25 @@ impl PrivateKey {
.map_err(|e| JsError::from_str(&format!("{}", e)))
}

/// Get private key from its bech32 representation
/// ```javascript
/// PrivateKey.from_bech32('ed25519_sk1ahfetf02qwwg4dkq7mgp4a25lx5vh9920cr5wnxmpzz9906qvm8qwvlts0');
/// ```
/// For an extended 25519 key
/// ```javascript
/// PrivateKey.from_bech32('ed25519e_sk1gqwl4szuwwh6d0yk3nsqcc6xxc3fpvjlevgwvt60df59v8zd8f8prazt8ln3lmz096ux3xvhhvm3ca9wj2yctdh3pnw0szrma07rt5gl748fp');
/// ```
pub fn from_bech32(bech32_str: &str) -> Result<PrivateKey, JsError> {
crypto::SecretKey::try_from_bech32_str(&bech32_str)
.map(key::EitherEd25519SecretKey::Extended)
.or_else(|_| {
crypto::SecretKey::try_from_bech32_str(&bech32_str)
.map(key::EitherEd25519SecretKey::Normal)
})
.map(PrivateKey)
.map_err(|_| JsError::from_str("Invalid secret key"))
}

pub fn to_bech32(&self) -> String {
match self.0 {
key::EitherEd25519SecretKey::Normal(ref secret) => secret.to_bech32_str(),
Expand Down