RSA加解密

1. 問題

今天在寫一段RSA加解密的代碼挎春,代碼本身不復(fù)雜。

  private static final String RSA = "RSA";
  private static final String UTF8 = "UTF-8";
  private static final String KEY_STORE = "PKCS12";
  private static final String X509 = "X.509";


  private static final int MAX_ENCRYPT_BLOCK = 117;
  private static final int MAX_DECRYPT_BLOCK = 128;

  public static byte[] encryptToBase64(byte[] originalContent, Key key) throws NoSuchPaddingException,
      NoSuchAlgorithmException, InvalidKeyException, IOException, BadPaddingException, IllegalBlockSizeException {
    Cipher cipher = Cipher.getInstance(key.getAlgorithm());
    cipher.init(Cipher.ENCRYPT_MODE, key);
    //cipher一次能加密的長度有限制豆拨,因此需要分段加密
    byte[] originalBytes = originalContent;
    int totalLength = originalBytes.length;
    int offset = 0;
    ByteArrayOutputStream resultStream = new ByteArrayOutputStream();
    while (totalLength > offset) {
      byte[] encryptedBlock = cipher.doFinal(
          originalBytes, offset, Math.min(totalLength - offset, RSAUtils.MAX_ENCRYPT_BLOCK));
      resultStream.write(encryptedBlock);

      offset = offset + RSAUtils.MAX_ENCRYPT_BLOCK;
    }
    
    byte[] encryptedContent = resultStream.toByteArray();
    return encryptedContent;
  }

  public static byte[] decryptFromBase64(byte[] encryptedContent, Key key) throws NoSuchPaddingException,
      NoSuchAlgorithmException, InvalidKeyException, IOException, BadPaddingException, IllegalBlockSizeException {
    Cipher cipher = Cipher.getInstance(key.getAlgorithm());
    cipher.init(Cipher.DECRYPT_MODE, key);
    //cipher一次能解密的長度有限制直奋,因此需要分段解密
    byte[] encryptedBytes = encryptedContent;
    int totalLength = encryptedBytes.length;
    int offset = 0;
    ByteArrayOutputStream resultStream = new ByteArrayOutputStream();
    while (totalLength > offset) {
      int blockLength = Math.min(totalLength - offset, RSAUtils.MAX_DECRYPT_BLOCK);
      byte[] decryptedBlock = cipher.doFinal(encryptedBytes, offset, blockLength);
      resultStream.write(decryptedBlock);

      offset = offset + RSAUtils.MAX_DECRYPT_BLOCK;
    }
    resultStream.close();
    byte[] originalContent = resultStream.toByteArray();
    return originalContent;
  }

但是在執(zhí)行單元測試的時候,總是報(bào)如下的錯誤

javax.crypto.BadPaddingException: Decryption error

    at sun.security.rsa.RSAPadding.unpadV15(RSAPadding.java:379)
    at sun.security.rsa.RSAPadding.unpad(RSAPadding.java:290)
    at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:365)
    at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:391)
    at javax.crypto.Cipher.doFinal(Cipher.java:2226)
    at wang.afrag.base.util.RSAUtils.decryptFromBase64(RSAUtils.java:72)
    at wang.afrag.base.util.RSAUtilsTest.testEncrypt(RSAUtilsTest.java:86)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:686)
    at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
    at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
    at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:212)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:208)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:137)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:71)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.util.ArrayList.forEach(ArrayList.java:1259)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.util.ArrayList.forEach(ArrayList.java:1259)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:248)
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$5(DefaultLauncher.java:211)
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:226)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:199)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:132)
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:71)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:220)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:53)

2. 解決的方法

經(jīng)過一番折騰施禾,總算是找到了原因脚线,在這里記錄下來。

主要的原因在于加密和解密是的block size弥搞,也就是 MAX_ENCRYPT_BLOCK 和 MAX_DECRYPT_BLOCK 這兩個常量的值邮绿。這兩個值必須和使用的密鑰的長度匹配渠旁。 我使用的密鑰是2048 bit的密鑰,因此這兩個值設(shè)置的長度分別應(yīng)該分別設(shè)置為245和256船逮。

3. 根本的原因

在進(jìn)行RSA加密的時候顾腊,必須考慮密鑰長度,明文長度和密文長度挖胃。

3.1 密鑰及密鑰長度

在RSA中杂靶,我們常說的密鑰,其實(shí)指的是 (公鑰 + 模值)冠骄、或(私鑰 + 模值)中的一組伪煤。 這一組中的數(shù)據(jù)是需要配合起來使用的。

我們所說的密鑰長度凛辣,指的是模值的位長度抱既。目前主流的密鑰長度是在1024bit以上,上不封頂扁誓。

3.2 加解密數(shù)據(jù)塊的長度

由于密鑰的長度是有限的防泵,因此一次能夠加/解密的長度也是有限的,和密鑰的長度是相同的蝗敢。但是要注意到捷泞,我們所說的密鑰長度,單位是bit寿谴。但是我們在計(jì)算明文或者密文的長度的時候锁右,通常單位是byte,因此要除以8讶泰。比如我用的密鑰長度是2048咏瑟,除以8之后為256, 因此我一次能夠加密或者解密的數(shù)據(jù)的最大長度是256個byte痪署。如果需要加密或者解密的數(shù)據(jù)多于這個值怎么辦码泞?答案是分塊處理,前面代碼中就是這樣處理的狼犯。

那為什么加密的數(shù)據(jù)塊大小和解密的數(shù)據(jù)塊大小不一致呢余寥?因?yàn)樵诩用艿臅r候,我們需要在明文中填充一些隨機(jī)數(shù)悯森,這樣每次產(chǎn)生的密文都會發(fā)生變化宋舷,這個過程稱為padding。在加密的過程中瓢姻,有各種各樣的padding標(biāo)準(zhǔn)肥缔,在前面的代碼中,采用的是默認(rèn)的PKCS1Padding標(biāo)準(zhǔn)汹来,這個標(biāo)準(zhǔn)中生成的隨機(jī)數(shù)要占用11個字節(jié)续膳,因此明文最長只能取245個字節(jié),合起來是256個字節(jié)收班。

4 其他

在RSA中坟岔,還有很多其他的Padding類型,例如使用OAEP算法的OAEPWITHSHA-256ANDMGF1PADDING等摔桦,這些Padding對應(yīng)的密文長度社付,就需要各位自己去發(fā)現(xiàn)了……

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市邻耕,隨后出現(xiàn)的幾起案子鸥咖,更是在濱河造成了極大的恐慌,老刑警劉巖兄世,帶你破解...
    沈念sama閱讀 218,682評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件啼辣,死亡現(xiàn)場離奇詭異,居然都是意外死亡御滩,警方通過查閱死者的電腦和手機(jī)鸥拧,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,277評論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來削解,“玉大人富弦,你說我怎么就攤上這事》胀裕” “怎么了腕柜?”我有些...
    開封第一講書人閱讀 165,083評論 0 355
  • 文/不壞的土叔 我叫張陵,是天一觀的道長矫废。 經(jīng)常有香客問我盏缤,道長,這世上最難降的妖魔是什么磷脯? 我笑而不...
    開封第一講書人閱讀 58,763評論 1 295
  • 正文 為了忘掉前任蛾找,我火速辦了婚禮,結(jié)果婚禮上赵誓,老公的妹妹穿的比我還像新娘打毛。我一直安慰自己,他們只是感情好俩功,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,785評論 6 392
  • 文/花漫 我一把揭開白布幻枉。 她就那樣靜靜地躺著,像睡著了一般诡蜓。 火紅的嫁衣襯著肌膚如雪熬甫。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,624評論 1 305
  • 那天蔓罚,我揣著相機(jī)與錄音椿肩,去河邊找鬼瞻颂。 笑死,一個胖子當(dāng)著我的面吹牛郑象,可吹牛的內(nèi)容都是我干的贡这。 我是一名探鬼主播,決...
    沈念sama閱讀 40,358評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼厂榛,長吁一口氣:“原來是場噩夢啊……” “哼盖矫!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起击奶,我...
    開封第一講書人閱讀 39,261評論 0 276
  • 序言:老撾萬榮一對情侶失蹤辈双,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后柜砾,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體湃望,經(jīng)...
    沈念sama閱讀 45,722評論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,900評論 3 336
  • 正文 我和宋清朗相戀三年局义,在試婚紗的時候發(fā)現(xiàn)自己被綠了喜爷。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,030評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡萄唇,死狀恐怖檩帐,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情另萤,我是刑警寧澤湃密,帶...
    沈念sama閱讀 35,737評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站四敞,受9級特大地震影響泛源,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜忿危,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,360評論 3 330
  • 文/蒙蒙 一达箍、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧铺厨,春花似錦缎玫、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,941評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至洼裤,卻和暖如春邻辉,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,057評論 1 270
  • 我被黑心中介騙來泰國打工值骇, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留莹菱,地道東北人。 一個月前我還...
    沈念sama閱讀 48,237評論 3 371
  • 正文 我出身青樓雷客,卻偏偏與公主長得像芒珠,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子搅裙,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,976評論 2 355

推薦閱讀更多精彩內(nèi)容

  • 加密分為對稱加密,非對稱加密裹芝, 不可逆加密部逮。 對稱加密:描述: 加密解密使用同樣的密鑰。特點(diǎn): 速度快嫂易,安全性一般...
    熾熱冰峰閱讀 3,613評論 0 0
  • 首先需要知道的關(guān)于rsa的知識 RSA與AES兄朋,DES一樣也是一個塊加密函數(shù) RSA常用的密鑰長度為 1024bi...
    徐浩友閱讀 8,101評論 2 3
  • RSA號稱地球上最安全的加密算法,https怜械、ssl颅和、網(wǎng)銀密碼等大多都是基于RSA加密的。那么RSA的基本原理是什...
    掌雄閱讀 10,058評論 0 3
  • 在做項(xiàng)目中為了安全考慮會對數(shù)據(jù)進(jìn)行加密缕允,這里使用了RSA進(jìn)行加密峡扩。總結(jié)如下:特點(diǎn):公鑰加密私鑰解密障本;私鑰簽名公鑰認(rèn)...
    IDO0閱讀 751評論 0 1
  • RSA 是非對稱加密教届,公鑰加密,私鑰解密驾霜, 反之亦然案训。缺點(diǎn):運(yùn)行速度慢,不易于硬件實(shí)現(xiàn)粪糙。常私鑰長度有512bit强霎,...
    和你一起666閱讀 777評論 0 0