-1
下面的清單可依使用量是我的代碼斯卡拉,我得到了密碼相同數量用明文
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)和純文本的數量。但是我得到了兩個不同數量純文本的相同數量的密碼。任何人都可以幫助我?
**切勿將RSA用作分組密碼**。您應該使用AES來代替。 –
*「即使純文本數量改變,我也得到了相同數量的密碼」* - 您能舉幾個例子嗎?請[編輯]你的問題,包括他們。我知道它會是什麼,但我想確定。 –
@ArtjomB。當然,我將目前爲1Mb的純文本(E:\\ plaintext.txt)更改爲。我在此輸出的下一個純文本是2 Mb。但是,兩個不同數量的純文本獲得相同的密碼量。 –