[java, kotlin] 안드로이드 암호화(md5, sha256)

천현철·2021년 1월 21일
0

Android

목록 보기
16/43
post-custom-banner

md5 로 암호화

java:

public static String md5(String str){
    String MD5 = "";
    try{
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(str.getBytes("UTF-8"));
        byte byteData[] = md.digest();
        StringBuffer sb = new StringBuffer();
        for(int i = 0 ; i < byteData.length ; i++)
            sb.append(Integer.toString((byteData[i]&0xff) + 0x100, 16).substring(1));
        MD5 = sb.toString();
    }
    catch(NoSuchAlgorithmException e) { e.printStackTrace(); MD5 = null; }
    catch (UnsupportedEncodingException e) { e.printStackTrace(); MD5 = null; }
    return MD5;
}

kotlin:

private fun md5(input:String): String {
    val md = MessageDigest.getInstance("MD5")
    return BigInteger(1, md.digest(input.toByteArray())).toString(16).padStart(32, '0')
}

출처
https://stackoverflow.com/questions/64171624/how-to-generate-an-md5-hash-in-kotlin

sha256 로 암호화

public static String sha256(String str) {
    String SHA = "";
    try{
        MessageDigest sh = MessageDigest.getInstance("SHA-256");
        sh.update(str.getBytes());
        byte byteData[] = sh.digest();
        StringBuffer sb = new StringBuffer();
        for(int i = 0 ; i < byteData.length ; i++)
            sb.append(Integer.toString((byteData[i]&0xff) + 0x100, 16).substring(1));
        SHA = sb.toString();
    }catch(NoSuchAlgorithmException e) { e.printStackTrace(); SHA = null; }
    return SHA;
}

[objective-c] md5 encode 하기

profile
기도하지말고 행동하라
post-custom-banner

0개의 댓글