kotlin AES、DES、RSA、MD5、SHA1、SHA256对称加密非对称加密简单实现(工具类)

一 : 对称加密(DES、AES)

1.DES

object Des {

    //学习查看api

    //算法/工作模式/填充模式

//    val transformation  = "DES/ECB/PKCS5Padding"

    val transformation  = "DES/CBC/PKCS5Padding"

    val algorithm  = "DES"

    fun encrypt(input:String,password:String):String{

//        val input = "欢迎来到花花世界"

//        var password = "12345678"

        val cipher = Cipher.getInstance(transformation)

        val instance = SecretKeyFactory.getInstance(algorithm)

        var keySpec = DESKeySpec(password.toByteArray())

        val key: Key? = instance.generateSecret(keySpec)

        val  iv = IvParameterSpec(password.toByteArray())

        cipher.init(Cipher.ENCRYPT_MODE,key,iv)//需要额外的参数

        val doFinal = cipher.doFinal(input.toByteArray())

        println("加密后字节数据长度 :" + doFinal.size)

        //base64编码

       return Base64.encode(doFinal)

    }

    fun descrypt(input:String,password:String):ByteArray{

//        val input = "欢迎来到花花世界"

//        var password = "12345678"

        val cipher = Cipher.getInstance(transformation)

        val instance = SecretKeyFactory.getInstance(algorithm)

        var keySpec = DESKeySpec(password.toByteArray())

        val key: Key? = instance.generateSecret(keySpec)

        val  iv = IvParameterSpec(password.toByteArray())

        cipher.init(Cipher.DECRYPT_MODE,key,iv)

        val doFinal = cipher.doFinal(Base64.decode(input))

        return doFinal

    }

}

fun main(args: Array<String>) {

    val input = "欢迎"

var password = "12345678"//密码必须是8位

    val toByteArray = input.toByteArray()

    println(toByteArray.size)

    toByteArray.forEach {

        println(it)

    }

    val encrypt = Des.encrypt(input, password)

    println(encrypt)//加密后变长啦

    val descrypt = Des.descrypt(encrypt, password)

    println(String(descrypt))

}

2 : AES

fun main(args: Array<String>) {

val password ="1234567812345678"//密码必须是16位

    val input ="欢迎"

    val encrypt = Aes.encrypt(input, password)

println(encrypt)

val decrypt = Aes.Decrypt(encrypt, password)

println(decrypt)

}

object Aes{

fun encrypt(input:String,password:String): String {

val instance = Cipher.getInstance("AES")

val keySpec:SecretKeySpec? = SecretKeySpec(password.toByteArray(),"AES")

instance.init(Cipher.ENCRYPT_MODE,keySpec)

val doFinal = instance.doFinal(input.toByteArray())

return Base64.encode(doFinal)

}

fun Decrypt(input:String,password:String):String {

val instance = Cipher.getInstance("AES")

val keySpec:SecretKeySpec? = SecretKeySpec(password.toByteArray(),"AES")

instance.init(Cipher.DECRYPT_MODE,keySpec)

val doFinal = instance.doFinal(Base64.decode(input))

return String(doFinal)

}

}

二 : 非对称加密(RSA)

object RSACrypt {

val transformation ="RSA"

    val ENCYPT_SISE =117

    val ENCYPT_MAX_SISE =128

    fun encryptBrPrivateKey(intput:String,privateKey:PrivateKey): String {

val inputArray = intput.toByteArray()

var temp:ByteArray? =null

        var offset =0//偏一

        val byteArrayOutputStream = ByteArrayOutputStream()

val cipher = Cipher.getInstance(transformation)

cipher.init(Cipher.ENCRYPT_MODE,privateKey)

//拆成几个部分

        while (inputArray.size - offset >0){

if (inputArray.size - offset >=ENCYPT_SISE){

temp = cipher.doFinal(inputArray,offset,ENCYPT_SISE)

offset +=ENCYPT_SISE

            }else{

temp = cipher.doFinal(inputArray,offset,inputArray.size - offset)

offset = inputArray.size

            }

byteArrayOutputStream.write(temp)

}

byteArrayOutputStream.close()

return Base64.encode( byteArrayOutputStream.toByteArray())

}

fun encryptBrPublicKey(intput:String,privateKey:PublicKey): String {

val inputArray = intput.toByteArray()

var temp:ByteArray? =null

        var offset =0//偏一

        val byteArrayOutputStream = ByteArrayOutputStream()

val cipher = Cipher.getInstance(transformation)

cipher.init(Cipher.ENCRYPT_MODE,privateKey)

//拆成几个部分

        while (inputArray.size - offset >0){

if (inputArray.size - offset >=ENCYPT_SISE){

temp = cipher.doFinal(inputArray,offset,ENCYPT_SISE)

offset +=ENCYPT_SISE

            }else{

temp = cipher.doFinal(inputArray,offset,inputArray.size - offset)

offset = inputArray.size

            }

byteArrayOutputStream.write(temp)

}

byteArrayOutputStream.close()

return Base64.encode( byteArrayOutputStream.toByteArray())

}

fun decryptBrPublicKey(intput:String,privateKey:PublicKey): String {

val inputArray = Base64.decode(intput)

var temp:ByteArray? =null

        var offset =0//偏一

        val byteArrayOutputStream = ByteArrayOutputStream()

val cipher = Cipher.getInstance(transformation)

cipher.init(Cipher.DECRYPT_MODE,privateKey)

//拆成几个部分

        while (inputArray.size - offset >0){

if (inputArray.size - offset >=ENCYPT_MAX_SISE){

temp = cipher.doFinal(inputArray,offset,ENCYPT_MAX_SISE)

offset +=ENCYPT_MAX_SISE

            }else{

temp = cipher.doFinal(inputArray,offset,inputArray.size - offset)

offset = inputArray.size

            }

byteArrayOutputStream.write(temp)

}

byteArrayOutputStream.close()

return String( byteArrayOutputStream.toByteArray())

}

fun desryptBrPrivateKey(intput:String,privateKey:PrivateKey): String {

val inputArray = Base64.decode(intput)

var temp:ByteArray? =null

        var offset =0//偏一

        val byteArrayOutputStream = ByteArrayOutputStream()

val cipher = Cipher.getInstance(transformation)

cipher.init(Cipher.DECRYPT_MODE,privateKey)

//拆成几个部分

        while (inputArray.size - offset >0){

if (inputArray.size - offset >=ENCYPT_MAX_SISE){

temp = cipher.doFinal(inputArray,offset,ENCYPT_MAX_SISE)

offset +=ENCYPT_MAX_SISE

            }else{

temp = cipher.doFinal(inputArray,offset,inputArray.size - offset)

offset = inputArray.size

            }

byteArrayOutputStream.write(temp)

}

byteArrayOutputStream.close()

return String( byteArrayOutputStream.toByteArray())

}

}

fun main(args: Array<String>) {

//生成密钥对:密钥对

    val instance = KeyPairGenerator.getInstance("RSA")//密钥生成器

    val genKeyPair = instance.genKeyPair()

val publicKey = genKeyPair.public

    val privateKey = genKeyPair.private

    println("公钥 : " + Base64.encode(publicKey.encoded))

println("私钥 : " + Base64.encode(privateKey.encoded))

var publicKeyStr ="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCbS0YjpJWh/IOwe40IY61FNyUBn2PYbDp0Oi5cvMTAgNtOfstrxlJrMV/A206IrpXB6Lm/eUZov4n42gjW2PbqfG6Prew3+r/u2ZjG5AUJPh/sTGln0kFr4zqykvy8qdeqpnJawkuhDfos+CAGDv8uibYCi+gvARS8HGEnbv6nPQIDAQAB"

    var privateKeyStr ="MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAJtLRiOklaH8g7B7jQhjrUU3JQGfY9hsOnQ6Lly8xMCA205+y2vGUmsxX8DbToiulcHoub95Rmi/ifjaCNbY9up8bo+t7Df6v+7ZmMbkBQk+H+xMaWfSQWvjOrKS/Lyp16qmclrCS6EN+iz4IAYO/y6JtgKL6C8BFLwcYSdu/qc9AgMBAAECgYA2DozayWbg3UKGA2wDeJcPGfQCzZX29y2d2cbbt0YR8IjmmRJ8cKut7qDzRCPhRkyRFE7cTP3qZopDmroq95lzV5psAJJUXWG/0ZQifZuI2F1toeAzGRdIuuZDClSF4J9xDA/WH9wg/quHKqwbD2sOkayBAIOY1xXGhrZ1s2uhTQJBAOvIoy35HKjkfXFl10cToAQS7PbLJVCoUkdStu1lZydb9pBASIqlVSf4A++dYSe2lfUCx3qFK61DtF2ImcnaVtMCQQCom+skXag+p9fvjif7fxz847w/dRC5QNUWYS1/gntY+H3+Gp2jiwppOpLOdSLiHsuhmq5tLz5SxBiVcCdIR1+vAkBqDqLP4BjzI2wFoQCXuQ0mJ/ks/a24PS5dZKhh2lXvD1+1/SRkMQA/7UCf/JOiEHAdeHWP9+zwj97Gn9ZFRI//AkBz71n9FGUmR/TDpIS7eojtHo6HN7B7ISgkDkfhoE++OocvnQ99r5JGDt95FLQatUAha6G6M7zv3iRlRMvN+D3DAkAxY6zV4Lwy/OyIsO/LfnN5c833Y9O4lQuvDqsUzYw2oOiZwepvxnqovOPhL+PjssZfVinkRLKRS86TPjQUFbVr"

    val instance1 = KeyFactory.getInstance("RSA")

val privateKeyS:PrivateKey = instance1.generatePrivate(PKCS8EncodedKeySpec(Base64.decode(privateKeyStr)))

val publicKeyS:PublicKey = instance1.generatePublic(X509EncodedKeySpec(Base64.decode(publicKeyStr)))

val input ="你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好"

    println("字符串长度 :" + input.length)

println("字符串字节长度 :" + input.toByteArray().size)//RSE不能超过117个字节

    val encryptBrPrivateKey = RSACrypt.encryptBrPrivateKey(input, privateKeyS)

println("私钥加密 : " + encryptBrPrivateKey)

val encryptBrPublicKey = RSACrypt.encryptBrPublicKey(input, publicKeyS)

println("公钥加密 : " + encryptBrPublicKey)

val desryptBrPrivateKey = RSACrypt.desryptBrPrivateKey(encryptBrPublicKey, privateKeyS)

println("私钥解密 : " + desryptBrPrivateKey)

val decryptBrPublicKey = RSACrypt.decryptBrPublicKey(encryptBrPrivateKey, publicKeyS)

println("公钥解密 : " + decryptBrPublicKey)

//******************************************

//    val input = "你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好"

//    println("字符串长度 :" + input.length)

//    println("字符串字节长度 :" + input.toByteArray().size)//RSE不能超过117个字节

//    val encryptBrPrivateKey = RSACrypt.encryptBrPrivateKey(input, privateKey)

//    println("私钥加密 :" + encryptBrPrivateKey)

//    val encryptBrPublicKey = RSACrypt.encryptBrPublicKey(input, publicKey)

//    println("公钥加密 :" + encryptBrPublicKey)

//    val desryptBrPrivateKey = RSACrypt.desryptBrPrivateKey(encryptBrPublicKey, privateKey)

//    println("私钥解密 :" + desryptBrPrivateKey)

//

//    val decryptBrPublicKey = RSACrypt.decryptBrPublicKey(encryptBrPrivateKey, publicKey)

//    println("公钥解密 :" + decryptBrPublicKey)

}

三 :MD5、SHA1、SHA256

object MessageDigetUtils {

/**

    * 转为16进制

    */

    fun toHex(byteArray:ByteArray): String {

var str =with(StringBuilder()){

            //转为字符串

            byteArray.forEach {

                //        println(it)

                var value =it

                var hex = value.toInt() and  (0xFF)

val toHexString = Integer.toHexString(hex)

if (toHexString.length ==1){

this.append("0" + toHexString)

}else{

this.append(toHexString)

}

}

            println(this.length)

return this.toString()

}

        return str

}

fun md5(input:String): String {

val md = MessageDigest.getInstance("MD5")

val digest = md.digest(input.toByteArray())

println("MD5加密前 : " + digest.size)

return toHex(digest)

}

fun sha1(intput:String): String {

val instance = MessageDigest.getInstance("SHA-1")

val digest = instance.digest(intput.toByteArray())

println("SHA-1加密前 : " + digest.size)

return toHex(digest)

}

fun sha256(intput:String): String {

val instance = MessageDigest.getInstance("SHA-256")

val digest = instance.digest(intput.toByteArray())

println("SHA-256加密前 : " + digest.size)

return toHex(digest)

}

}

fun main(args: Array<String>) {

var mChar:String ="你好不开心"

    val md5 = MessageDigetUtils.md5(mChar)

println(md5)

println(md5.toByteArray().size)

val sha1 = MessageDigetUtils.sha1(mChar)

println(sha1)

println(sha1.toByteArray().size)

val sha256 = MessageDigetUtils.sha256(mChar)

println(sha256)

println(sha256.toByteArray().size)

}

四 :数字签名

object SignatureDemo {

fun sign(input:String,privateKey:PrivateKey): String {

val instance = Signature.getInstance("SHA256withRSA")

instance.initSign(privateKey)

instance.update(input.toByteArray())

val sign = instance.sign()

return Base64.encode(sign)

}

fun verify(input: String,publicKey:PublicKey,sign:String): Boolean {

val instance = Signature.getInstance("SHA256withRSA")

instance.initVerify(publicKey)

instance.update(input.toByteArray())

//校验

        val verify = instance.verify(Base64.decode(sign))

return verify

}

}

fun main(args: Array<String>) {

val input:String ="你好不开心呢"

    val privateKey = RSACrypt.getPrivateKey()

val sign = SignatureDemo.sign(input, privateKey)

println(sign)

//***************jiaoyan************************

    val verify = SignatureDemo.verify(input, RSACrypt.getPublicKey(), sign)

println(verify)

}

注意Base64类在此:

object Base64 {

private val base64EncodeChars =charArrayOf('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/')

private val base64DecodeChars =byteArrayOf(-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1)

fun encode(data: ByteArray): String {

val sb = StringBuffer()

val len = data.size

        var i =0

        var b1: Int

var b2: Int

var b3: Int

while (i < len) {

b1 = ((data[i++]).toInt() and0xff).toInt()

if (i == len) {

sb.append(base64EncodeChars[b1.ushr(2)])

sb.append(base64EncodeChars[b1 and0x3 shl4])

sb.append("==")

break

            }

b2 = (data[i++]).toInt() and0xff

            if (i == len) {

sb.append(base64EncodeChars[b1.ushr(2)])

sb.append(base64EncodeChars[b1 and0x03 shl4 or (b2 and0xf0).ushr(4)])

sb.append(base64EncodeChars[b2 and0x0f shl2])

sb.append("=")

break

            }

b3 = (data[i++]).toInt() and0xff

            sb.append(base64EncodeChars[b1.ushr(2)])

sb.append(base64EncodeChars[b1 and0x03 shl4 or (b2 and0xf0).ushr(4)])

sb.append(base64EncodeChars[b2 and0x0f shl2 or (b3 and0xc0).ushr(6)])

sb.append(base64EncodeChars[b3 and0x3f])

}

return sb.toString()

}

@Throws(UnsupportedEncodingException::class)

fun decode(str: String): ByteArray {

val sb = StringBuffer()

val data = str.toByteArray(charset("US-ASCII"))

val len = data.size

        var i =0

        var b1: Int

var b2: Int

var b3: Int

var b4: Int

while (i < len) {

/* b1 */

            do {

b1 =base64DecodeChars[(data[i++]).toInt()].toInt()

}while (i < len && b1 == -1)

if (b1 == -1)break

            /* b2 */

            do {

b2 =base64DecodeChars[(data[i++]).toInt()].toInt()

}while (i < len && b2 == -1)

if (b2 == -1)break

            sb.append((b1 shl2 or (b2 and0x30).ushr(4)).toChar())

/* b3 */

            do {

b3 = data[i++].toInt()

if (b3 ==61)return sb.toString().toByteArray(charset("ISO-8859-1"))

b3 =base64DecodeChars[b3].toInt()

}while (i < len && b3 == -1)

if (b3 == -1)break

            sb.append((b2 and0x0f shl4 or (b3 and0x3c).ushr(2)).toChar())

/* b4 */

            do {

b4 = data[i++].toInt()

if (b4 ==61)return sb.toString().toByteArray(charset("ISO-8859-1"))

b4 =base64DecodeChars[b4].toInt()

}while (i < len && b4 == -1)

if (b4 == -1)break

            sb.append((b3 and0x03 shl6 or b4).toChar())

}

return sb.toString().toByteArray(charset("ISO-8859-1"))

}

}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,013评论 6 481
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,205评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 152,370评论 0 342
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,168评论 1 278
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,153评论 5 371
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,954评论 1 283
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,271评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,916评论 0 259
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,382评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,877评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,989评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,624评论 4 322
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,209评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,199评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,418评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,401评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,700评论 2 345

推荐阅读更多精彩内容