一 : 对称加密(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"))
}
}