欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Groovy DES加解密

程序员文章站 2024-03-14 14:12:58
...
import java.security.*
import javax.crypto.*
import javax.crypto.spec.*

class DESCodec {
static encode = { String target ->
def cipher = getCipher(Cipher.ENCRYPT_MODE)
return cipher.doFinal(target.bytes).encodeBase64()
}

static decode = { String target ->
def cipher = getCipher(Cipher.DECRYPT_MODE)
return new String(cipher.doFinal(target.decodeBase64()))
}

private static getCipher(mode) {
def keySpec = new DESKeySpec(getPassword())
def cipher = Cipher.getInstance("DES")
def keyFactory = SecretKeyFactory.getInstance("DES")
cipher.init(mode, keyFactory.generateSecret(keySpec))
return cipher
}

private static getPassword() { "secret12".getBytes("UTF-8") }

static void main(args) {
def strmi=encode("asdtiang")
//println decode("asdtiang")
//DESCodec.decode strmi
println decode("${strmi}")////这个地主一定要这样写,由于理论不深入,具体为什么还不明白,写成strmi 是不正确的。
///或者写成strmi.toString()也行,不过还没实践过。

}
}