下面列出的是我的代码
import java.security._
import java.security.spec.X509EncodedKeySpec
import javax.crypto._
import org.apache.commons.codec.binary.Base64
import scala.io.Source
import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
import java.util.logging.Logger
object RSA {
def bytes2hex(bytes: Array[Byte]): String = {
val hex = new StringBuilder()
for (i <- 0 to bytes.length - 1) {
val b = bytes(i)
var negative = false
if (b < 0) {
negative = true
}
val inte = Math.abs(b)
val temp = Integer.toHexString(inte & 0xFF)
if (temp.length() == 1) {
hex.append("0")
}
// hex.append(temp.toLowerCase())
hex.append(temp)
}
hex.toString
}
def decodePublicKey(encodedKey: String):Option[PublicKey] = {
this.decodePublicKey(
(new Base64()).decode(encodedKey)
)
}
def decodePublicKey(encodedKey: Array[Byte]): Option[PublicKey]= {
scala.util.control.Exception.allCatch.opt {
val spec = new X509EncodedKeySpec(encodedKey)
val factory = KeyFactory.getInstance("RSA")
factory.generatePublic(spec)
}
}
def encrypt(file: String,key:PublicKey): Array[Byte] = {
val cipher = Cipher.getInstance("RSA")
cipher.init(Cipher.ENCRYPT_MODE, key)
val text = Source.fromFile(file)
val list=text.toList
val blocks=list.grouped(501)
val iter=blocks.formatted()
val words=iter.getBytes
cipher.doFinal(words)
}
def main(args:Array[String]):Unit={
val publicKey=decodePublicKey("--4096bits RSA public keys--")
val cipher = encrypt("E:\\plaintext.txt",publicKey.get)
println("Cipher is "+ bytes2hex(cipher))
}
}`
这里我要加密的纯文本(“E:\ plaintext.txt”)大约是1 Mb。 RSA密钥的最大长度为4096位,可加密的最大大小为501字节。我决定将我的文本分成2093个数组(1024 * 1024/501 = 2092.1)
我更改了纯文本(E:\ plaintext.txt),并且更改了纯文本的数量。但是我用两种不同的纯文本获得了相同数量的密码。任何可以帮助我的人?
答案 0 :(得分:0)
使用AES等对称加密来加密数据。
如果需要公钥/私钥对,则使用非对称加密(RSA)加密对称(AES)密钥。然后将AES加密数据和RSA加密密钥作为一个单元打包。这通常称为混合加密,实质上是HTTP的工作原理。