Android Study

해쉬값을 이용한 코드 보안(feat.Kotlin)

85chong 2022. 2. 10. 15:54
728x90
반응형
SMALL
fun testGetHashCode():String{
        var STREAM_BUFFER_LENGTH = 2048
        var appPath = ""
        var hash = ""
        var numBytes = 0
        try{
            var packageInfo = packageManager.getPackageInfo(packageName, PackageManager.GET_SIGNING_CERTIFICATES)
            //appPath 주소는 현재 패키지의 기본 base.apk 주소로 되어있음
            appPath = packageInfo.applicationInfo.sourceDir

            var fis = FileInputStream(appPath)
            var md = MessageDigest.getInstance("MD5")
            md.reset()
            val bytes = ByteArray(STREAM_BUFFER_LENGTH)

            numBytes = fis.read(bytes)

            while (numBytes!=-1){
                md.update(bytes,0,numBytes)
                numBytes = fis.read(bytes)
            }
            var digest:ByteArray = md.digest()
            var sb = StringBuffer()
            for(i in 0 until digest.size){
                sb.append(Integer.toString((digest[i] and 0xff) + 0x100, 16).substring(1))
            }
            hash = sb.toString()
        }catch (e:Exception){
            android.util.Log.e("yck","e() : ${e}")
        }
        return hash.trim()
    }