All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.isyscore.gmssl.Sm4Ctr.kt Maven / Gradle / Ivy

The newest version!
package com.isyscore.gmssl

import org.gmssl.GmSSLJNI

class Sm4Ctr {

    companion object {
        @JvmStatic
        val KEY_SIZE = GmSSLJNI.SM4_KEY_SIZE

        @JvmStatic
        val IV_SIZE = GmSSLJNI.SM4_BLOCK_SIZE

        @JvmStatic
        val BLOCK_SIZE = GmSSLJNI.SM4_BLOCK_SIZE
    }

    private val sm4CtrCtx = GmSSLJNI.sm4_ctr_ctx_new()
    private var inited = false

    init {
        if (sm4CtrCtx == 0L) throw GmSSLException(SM4_CTR_CTX_ERROR)
    }

    fun init(key: ByteArray, iv: ByteArray) {
        if (key.size != KEY_SIZE || iv.size != IV_SIZE) throw GmSSLException(SM4_CTR_INIT_PARAM_INVALID)
        if (GmSSLJNI.sm4_ctr_encrypt_init(this.sm4CtrCtx, key, iv) != 1) throw GmSSLException(SM4_CTR_INIT_ERROR)
        this.inited = true
    }

    fun update(inData: ByteArray, inOffset: Int, inLen: Int, outData: ByteArray, outOffset: Int): Int {
        if (!this.inited) throw GmSSLException(SM4_CTR_UNINITED)
        if (inOffset < 0 || inLen < 0 || inOffset + inLen <= 0 || inData.size < inOffset + inLen) throw GmSSLException(SM4_CTR_UPDATE_PARAM_INVALID)
        if (outOffset < 0 || outData.size < outOffset) throw GmSSLException(SM4_CTR_UPDATE_PARAM_INVALID)
        val outLen = GmSSLJNI.sm4_ctr_encrypt_update(this.sm4CtrCtx, inData, inOffset, inLen, outData, outOffset)
        if (outLen < 0) throw GmSSLException(SM4_CTR_UPDATE_ERROR)
        return outLen
    }

    fun doFinal(out: ByteArray, outOffset: Int): Int {
        if (!this.inited) throw GmSSLException(SM4_CTR_UNINITED)
        if (outOffset < 0 || out.size < outOffset) throw GmSSLException(SM4_CTR_UPDATE_PARAM_INVALID)
        val outLen = GmSSLJNI.sm4_ctr_encrypt_finish(this.sm4CtrCtx, out, outOffset)
        if (outLen < 0) throw GmSSLException(SM4_CTR_UPDATE_ERROR)
        this.inited = true
        return outLen
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy