2009-11-10 178 views

回答

32

對於爲十六進制字符串

import java.security.*; 
public class Test { 
    public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchProviderException { 
     KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); 
     keyGen.initialize(512); 
     byte[] publicKey = keyGen.genKeyPair().getPublic().getEncoded(); 
     StringBuffer retString = new StringBuffer(); 
     for (int i = 0; i < publicKey.length; ++i) { 
      retString.append(Integer.toHexString(0x0100 + (publicKey[i] & 0x00FF)).substring(1)); 
     } 
     System.out.println(retString); 
    } 
} 

輸出作爲字節輸出值

import java.security.*; 
import java.security.*; 
public class Test { 
    public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchProviderException { 
     KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); 
     keyGen.initialize(512); 
     byte[] publicKey = keyGen.genKeyPair().getPublic().getEncoded(); 
     StringBuffer retString = new StringBuffer(); 
     retString.append("["); 
     for (int i = 0; i < publicKey.length; ++i) { 
      retString.append(publicKey[i]); 
      retString.append(", "); 
     } 
     retString = retString.delete(retString.length()-2,retString.length()); 
     retString.append("]"); 
     System.out.println(retString); //e.g. [48, 92, 48, .... , 0, 1] 
    } 
} 
+0

非常感謝您! 如果我應該得到這樣的結果[48,-137,-97,49,13,6,8,42,-122,72,-122,-9,13,2,3,15,4,0, 3,-132,-115,0,48,-127]我應該只使用toString方法而不是 retString.append(Integer.toHexString(0x0100 +(publicKey [i]&0x00FF))。substring(1)); ?? – Angela 2009-11-10 18:54:05

+0

檢查第二個代碼清單。 – jitter 2009-11-10 19:07:30

+1

如果我想以PEM格式輸出,那我該怎麼做? – Yatin 2015-05-20 04:13:20