Crypto
CryptoAPI provides hashing, MAC, key pair generation, signing, and legacy encryption. It is not always available - consult the Spotube host for current capability requirements.
Consuming
Obtain the service in main() and pass it to implementations that need crypto:
import dev.krtirtho.plugin_interfaces.host_apis.CryptoAPI
import dev.krtirtho.plugin_interfaces.host_apis.CryptoAPI_SERVICE_NAME
fun main() {
val crypto = zipline.take<CryptoAPI>(CryptoAPI_SERVICE_NAME)
zipline.bind<CoreAPI>(CoreAPI_SERVICE_NAME, RealCoreAPI(storage, crypto))
}
Receive it in your service class constructor. Most methods come in both suspend and blocking variants (suffixed Blocking).
Hashing
val data = "hello world".encodeToByteArray()
val hash = crypto.hash(HashAlgorithms.SHA256, data)
Message Authentication Codes
Generate a MAC key, then sign data with it:
val key = crypto.generateMACKey(MACKeyGeneratorAlgorithms.HMAC(HashAlgorithms.SHA256, HMACEncodingFormats.RAW))
val signature = crypto.signWithMACKey(MACSignatureAlgorithms.HMAC(HashAlgorithms.SHA256, HMACEncodingFormats.RAW), key, data)
val isValid = crypto.verifyMACSignatureWithKey(MACSignatureAlgorithms.HMAC(HashAlgorithms.SHA256, HMACEncodingFormats.RAW), key, signature, data)
Algorithms: HMAC(hashAlgorithm, format) and AES_CMAC(keySize, format).
Key pair generation
// ECDSA
val (publicKey, privateKey) = crypto.generateKeyPair(
GenerateKeyPairAlgorithms.ECDSA(ECCurves.P256, ECEncodingFormats.DER)
)
// EdDSA
val (publicKey, privateKey) = crypto.generateKeyPair(
GenerateKeyPairAlgorithms.EdDSA(EdDSACurves.Ed25519, EdDSAEncodingFormats.DER)
)
// RSA
val (publicKey, privateKey) = crypto.generateKeyPair(
GenerateKeyPairAlgorithms.RSA_PSS(HashAlgorithms.SHA256, keySizeBits = 2048)
)
Available curves: P256, P384, P521, secp256k1, brainpoolP256r1, brainpoolP384r1, brainpoolP512r1, Ed25519, Ed448.
Signing and verification
Sign data with a private key, then verify with the public key:
val (publicKey, privateKey) = crypto.generateKeyPair(
GenerateKeyPairAlgorithms.ECDSA(ECCurves.P256, ECEncodingFormats.DER)
)
val signature = crypto.signWithPrivateKey(
SignAlgorithms.ECDSA(ECCurves.P256, HashAlgorithms.SHA256, ECEncodingFormats.DER, ECDSASignatureFormats.DER),
data,
privateKey
)
val isValid = crypto.verifySignatureWithPublicKey(
SignAlgorithms.ECDSA(ECCurves.P256, HashAlgorithms.SHA256, ECEncodingFormats.DER, ECDSASignatureFormats.DER),
data,
signature,
publicKey
)
Encryption
val key = crypto.generateRandomBytes(8)
val iv = crypto.generateRandomBytes(8)
val cipherText = crypto.encryptLegacy(LegacyCipherAlgorithms.DES(SymmetricModes.ECB, PaddingTypes.PKCS7), key, data, iv)
val plainText = crypto.decryptLegacy(LegacyCipherAlgorithms.DES(SymmetricModes.ECB, PaddingTypes.PKCS7), key, cipherText, iv)
Crypto may require a capability declaration depending on the Spotube host version. Check the host documentation.